Sending Email with Payara and Gmail

Email was invented almost 50 years ago, yet the popularity of email is not going down. Nowadays with email it’s make more easier to communicate between co-workers, family, even with your friends. Talking about email I believe as software engineer you have one, two or maybe almost your application should have the requirements to be able send an email for example like send an activation user account, promotions, payment bills, and many more.

Requirements to be able send an email it’s have been exist a long time ago, you will find almost all programming language have the API to send an email and it’s not different with Java. Java, especially Java EE have an email API and the good news is JavaMail API (JSR 919) have a new update, and as Java Developer I would like to show you how easy to send an email using Java EE with of course, the wonderful Payara Application Server.

As you know Java EE is an standard including the JavaMail API, so in order to send an email you need the implementation of JavaMail API which is implemented by Application Server. Payara is a derived from Glassfish, an open-source Java EE Application Server that’s my reason to use Payara since I believe many of you, as Java Developer, have good relations with Glassfish. Using Payara you will feel the similarity when using Glassfish, with this you will easily to setup the JavaMail configuration.

Email Configuration on Payara

Payara team itself already give a good explanation about how to configure email resource, you can see on their blog. Coincidentally, their example was using Gmail which will be used on this tutorial. Why Gmail? Well, for the sake of simplicity and I believe many of you have Gmail account right? I would like to summarize how to configure JavaMail on Payara based on the official Payara team tutorial.

First, in order to configure your JavaMail you need to login into Payara Admin Console page then open menu Resources -> JavaMail -> Click New button to create new JavaMail datasource. You need to fill the requirements like this.

JavaMail Configuration
  • JNDI Name: JavaMail JNDI name.
  • Mail Host: smtp.gmail.com.
  • Default User: mail_address (remove @gmail.com)
  • Default Sender Address: valid_gmail_address

Next, you need to make sure to enable the debug checkbox when developing your software to make more easier and don’t forget to disabled it when ready to deploy into production.

Enable Debug Mode on Development.

The last, you need to add Additional Properties like this.

JavaMail Properties
  • mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
  • mail.smtp.socketFactory.port = 465
  • mail.smtp.port = 465
  • mail.smtp.auth = true
  • mail.smtp.password = gmail account password
  • mail.smtp.user = gmail address

This is not mentioned on Payara blog, but it’s also required during configure JavaMail with Gmail. As you know Gmail is the most valuable product from Google, so you can believe in their service and security, but this is also being a problem. Gmail will reject any application who want to access it without have a better security. Well, I don’t know what kind of security that Gmail require but knowing that you will execute this tutorial on your local machine Gmail will mark you as not secure application. So you need to turn of this feature from your Gmail account in Less Secure Apps menu.

Hack the Code

Sending an email with Java EE actually is pretty easy, I will show you with some code rather than boring theory explanation. First, you need to create a Class that responsibility was to send your email and mostly it’s come from javax.mail package.

@Stateless
public class EmailSender {
    @Resource(name = "java/mail/swhp")
Session mailSession;
}

You need pay attention on @Resource there you configure the JavaMail to looking for JavaMail configuration name, yes all of your configuration on Payara was injected with single annotations. Furthermore, this class was also annotated as @Stateless which is an EJB. EJB is not only about transaction, but there is still many more such as monitoring, pooling and many more. So, it’s more easier to have an EJB in EmailSender class.

Now, you are ready to write an method to send and email, below was simple example about how to send a simple message.

public void sendEmail() throw MessagingException, UnsupportedEncodingException {
Message message = new MimeMessage(mailSession);

message.setSubject("Hi");
message.setRecipient(Message.RecipientType.TO, new InternetAddress("random.client@gmail.com", "Random Guest"));
message.setText("Hello World!");
    Transport.send(message);
}

From code above you must realize that it’s just send a simple text, but how if you want to send something more html-ish? You just need to change the code slightly from message.setText() into message.setContent(), like this.

message.setContent(<p>Hello <b>World!</b></p>, "text/html; charset=utf-8");

You also not only can send to one recipient, but you can also perform a CC or send to more than one recipient, you just need to add more the recipient.

message.setRecipient(Message.RecipientType.TO, new InternetAddress("random.client@gmail.com", "Random Guest"));
message.setRecipient(Message.RecipientType.CC, new InternetAddress("boss.client@gmail.com", "Random Guest"));

Now, let’s talk about how to send an attachment in your email. You need to use MimeBodyPart to do that.

// Body text.
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here are the files.");
// Multipart message.
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Attachment file from string.
messageBodyPart = new MimeBodyPart();
messageBodyPart.setFileName("README1.txt");
messageBodyPart.setContent(new String("file 1 content"), "text/plain");
multipart.addBodyPart(messageBodyPart);
// Attachment file from file.
messageBodyPart = new MimeBodyPart();
messageBodyPart.setFileName("README2.txt");
DataSource src = new FileDataSource("file.txt");
messageBodyPart.setDataHandler(new DataHandler(src));
multipart.addBodyPart(messageBodyPart);
// Attachment file from byte array.
messageBodyPart = new MimeBodyPart();
messageBodyPart.setFileName("README3.txt");
src = new ByteArrayDataSource("file 3 content".getBytes(), "text/plain");
messageBodyPart.setDataHandler(new DataHandler(src));

multipart.addBodyPart(messageBodyPart);
// The last put this on MimeMessage
message.setContent(multipart);

The Conclusion

See how easy to send an email using only Java EE and Payara Application Server. You don’t need extra dependencies or hard and strange configuration to do that. I believe the configuration won’t be differ while using another Application Server such as TomEE or Wildfly which is give a freedom to Java Developer to choose and pick their favorite Application Server, and for me of course Payara is my favorite.

If you enjoyed reading this article, please recommend with click the 👏 below and share it to help others find it!