Send Mail from Liferay Portlet/Hook

Sending Mail from a Liferay Portlet or Hook is a pretty simple ordeal, although it becomes a bit tedious if not done correctly as I found out, after I had wasted more than a day trying to send it.

To send an email from liferay, firstly, we will have to setup the SMTP Server from which to send the email. You can use any SMTP, however, the easiest one to setup is the gmail smtp server. Since I am using Liferay version 6.1.1, I will be showing how to configure it in the same, i.e. with Control Panel GUI assistance.

To setup a SMTP server, you have to login as an administrator and go to the Control Panel. In Control Panel, go to Server Administration and then Mail.

In mail, you will have POP Server and SMTP Server. For now we are only interested in SMTP Server.

Fill out the SMTP fields as below :

SMTP Server : smtp.gmail.com
Port : 465[x] 
Use Secure Connection - check the box
User : Your gmail username
Password : Your gmail password

After that, open up your liferay hook or portlet project. And in the file liferay-plugin-package.properties, add the following line

portal-dependency-jars=\ ext\\mail.jar

This line will assure that the jar present in the ext folder of tomcat is used. Now, as my liferay hook/portlet projects were maven projects, the following will be for maven projects only.

In the pom.xml file of Maven Project, add the following dependencies,

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

The scope for javax.mail is an important factor. If the scope is not set to provided maven will download a jar file for use by the project which will cause dependency conflicts between the mail.jar pesent in tomcat’s ext directory and the one downloaded my maven.

To send email, we can use the following series of codes :

InternetAddress to = new InternetAddress(toEmailAddress, toName);
MailMessage mailMessage = new MailMessage();
mailMessage.setFrom(from);
mailMessage.setTo(to);
mailMessage.setBody("This is the body);
mailMessage.setSubject("This is the subject);
MailServiceUtil.sendEmail(mailMessage);

To send an email in HTML format, you can set in mailMessage as below :

mailMessage.setHTMLFormat(true);

The MailServiceUtil.sendEmail will send an email from liferay to the intended recipient.

Add a Comment

Your email address will not be published. Required fields are marked *