How to send mail from Liferay Portlet?


 import java.io.IOException;  
 import javax.mail.internet.AddressException;  
 import javax.mail.internet.InternetAddress;  
 import javax.portlet.ActionRequest;  
 import javax.portlet.ActionResponse;  
 import javax.portlet.PortletException;  
 import com.liferay.mail.service.MailServiceUtil;  
 import com.liferay.portal.kernel.mail.MailMessage;  
 import com.liferay.util.bridges.mvc.MVCPortlet;  
 /**  
  * Portlet implementation class FeedbackPortlet  
  */  
 public class FeedbackPortlet extends MVCPortlet {  
      public void sendEmail(ActionRequest actionRequest,  
                ActionResponse actionResponse) throws IOException, PortletException {  
           MailMessage mailMessage = new MailMessage();  
        mailMessage.setHTMLFormat(true);  
        mailMessage.setBody("Your mail body");  
        mailMessage.setFrom(new InternetAddress("from_mail_id@something.com","Display Name in Inbox"));  
        mailMessage.setSubject("Message From Feedback page...");  
        try {  
          mailMessage.setTo(new InternetAddress("to_mail_id@something.com"));  
        } catch (AddressException e) {  
          e.printStackTrace();  
        }  
        MailServiceUtil.sendEmail(mailMessage);   
        System.out.println("Sent Successfuly!!!");  
      }       
 }  


Before you go to run this portlet you have to make changes in Liferay configuration as below:

Step 1: Goto Liferay Control Panel
Step 2: In Configuration -> Click on Server Admninistration
Step 3: Then Goto Mail
Step 4: Fill out below fields(I am using GMail as my mail server),
a. Outgoing SMTP Server -> smtp.gmail.com
b. Outgoing Port  -> 465
c. Check -> Use a Secure Network Connection
d. User Name -> your_mail_id@gmail.com
e. Password -> your_gmail_password
Step 5: Click SAVE

Sometimes GMAIL can block the your application from sending mail as LESS SECURE application, in that case you again have to make change in gmail configuration as below:

Step 1: Goto Gmail Setting For Less Secure Applications
Step 2: Change setting for Access for less secure apps -> Turn on


Gmail Setting For Less Secure Applications
Gmail Setting For Less Secure Applications

Thats it, now you will be able to send mail from your portlet.

Comments

Popular posts from this blog

How to get context path in JQuery?

How to extend Liferay 6.2 session timeout by AJAX call?