dilbert-email

Sending E-mails with JavaMail on Glassfish V3

One of the main advantages of using an application server like Glassfish is to keep your application free of complex code, such as 1) manual control of database transactions; 2) database access configuration; 3) security authentication and authorization; 4) sending and receiving e-mail messages, among many other complexities that are non-functional requirements, consuming the time we would be spending on functional requirements.

In my opinion, an important differential of Glassfish V3 is its very rich and complete administration console. It is easy to use and to learn, which is, in my opinion, one of the most important competitive advantages, since it contributes to reduce the maintenance cost, a constant headache for system administrators. We have used the administrative console in a previous post to configure a database connection to PostgreSQL. Now, we are going to use it again in order to configure a JavaMail resource for applications that aim to send emails.

Follow the steps below:

  1. enter in the administrative console (http://[server-name]:4848/).
  2. go to Resources / JavaMail Sessions.
  3. create a new JavaMail session and set the following mandatory properties:
    JNDI Name: mail/[email-account-name]
    Mail Host: [smtp-server-address]
    Default User: the username to authenticate on the smtp server
    Default Return Address: the address used by recipients to reply the message. Some servers require that this address should be the one used by the authenticated user to access his mailbox.

If the server doesn’t request secure authentication, then the three steps above are enough to start using the new JavaMail session, but a server without secure authentication is a very rare case nowadays. You will certainly need to inform a password to login on the smtp server. In most cases, the server administrator also changes the default port of the smtp server, which forces us to explicitly inform the correct port. For these special needs we can use additional properties in the JavaMail session. Follow the steps below:

  1. Still on the JavaMail session form, go to the Additional Properties section and add 3 more properties, which are:
    mail.smtp.port: [port-number]
    mail.smtp.auth: true
    mail.smtp.password: ****** ;)
  2. Click on Save to create the JavaMail session.

The last step is how to use this new JavaMail session in our applications to send emails. Using the JNDI name, we are going to inject the JavaMail session in a Java class, which could be a POJO of a pure web application, an EJB Session Bean, or any other type of class. See the code below for details:

public class UserAccountBsn {
@Resource(name = “mail/[email-account-name]”)
private Session mailSession;

public void sendMessage(UserAccount userAccount) {
Message msg = new MimeMessage(mailSession);
try {
msg.setSubject(“[app] Email Alert”);
msg.setRecipient(RecipientType.TO,
new InternetAddress(userAccount.getEmail(),
userAccount.toString()));
msg.setText(“Hello “+ userAccount.getName());
Transport.send(msg);
}
catch(MessagingException me) {
// manage exception
}
catch(UnsupportedEncodingException uee) {
// manage exception
}
}
}

The @Resource annotation receives the JNDI name of the JavaMail session and injects an instance of the session in the variable mailSession. This variable is used within the sendMessage method to create a new MimeMessage. The content of the message is built and finally sent to the recipient by the method Transport.send. The method receives as parameter an entity class representing an user registered on the application. It is so simple, isn’t it? ;)

Using this feature, we avoid any additional implementation to add those parameters hardcoded or parameterized, saving a lot of time, simplifying the maintenance of the applications, and reusing existing resources naturally shared by the container.

16 thoughts on “Sending E-mails with JavaMail on Glassfish V3

  1. i think the class UserAccountBsn has to be a container managed class to make the source from above runnable… In other classes, eg a very simple POJO without any further annotations, @Resource will only inject “null”.

  2. I have my resource set up with Mail Host: smtp.bla. However, I am getting a connection failure with the host: localhost. How do I get this to use the resource mail host. I have even tried to add a mail.smtp.host property

  3. “smtp.bla” doesn’t seem to be a valid SMTP server. You need an email service provider, which could be your Internet provider, GMail, Yahoo and many others. They will give you instructions about a smtp address that you have access to, something like “smtp.google.com” or “smtp.aol.com”, but you need username and password to access the server. Unless your email service is running in your own machine, which is rare, you should not use localhost too.

  4. The main imports are:

    import java.io.UnsupportedEncodingException;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import javax.annotation.Resource;
    import javax.ejb.EJB;
    import javax.ejb.Stateless;
    import javax.ejb.LocalBean;
    import javax.mail.Message;
    import javax.mail.Message.RecipientType;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;

    The parameter “UserAccount” is a simple POJO to represent the user’s entity.

  5. What Mail host and port do you use? I use smtp.gmail.com with port 465, but it hang. Email never send out, does glassfish 3.1 b25 not work well with smtp.gmail.com?

  6. I use several hosts, but I never tried smtp.gmail.com. What is the error message produced by Glassfish? Usually the email server returns a description of the problem. In most of cases, it has nothing to do with the application server.

  7. That is the problem, it does not return any error at all. If I specify the port to 465, then it just hang (like your cursor keep spinning), if I dont specify the port, then it does not hang but it does not send mail either. In both cases, no error return to the server log. What hosts do you usually use?

  8. This work excellent, except for a little detail. The mail arrived without a FROM. TO, SUBJECT and TEXT get well, but not the FROM. Default from address is already set in GF javamail session.
    Which is the cause?

  9. Hello! The JavaMail API defines the property ‘from’ based on the value of the fields ‘Default User’ and ‘Default Return Address’, which are located in the section JavaMail Sessions of the Glassfish console. You should define the fields with the email address that you want to be the ‘from’.

Comments are closed.