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:
- enter in the administrative console (http://[server-name]:4848/).
- go to Resources / JavaMail Sessions.
- 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.
- 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: ****** ;) - Click on Save to create the JavaMail session.
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.




