How to send an email in Glassfish using JavaMail session injection

This tutorial will teach us how to send an email in Glassfish using JavaMail session injection. It use gmail for sending the email.

1.) First we need to create a JavaMail session by, opening Glassfish admin: http://localhost:4848, and navigating to Resources->JavaMail Sessions.

2.) Click "New" button and input the following values:
JNDI Name: mailSession
Mail Host:
Default User and Default Sender Address: any of your valid gmail account

3.) Leave Advance Setting unchange.

4.) On the Additional Properties section, we need to add the following properties:

5.) And finally a sample code that do the sending:

package com.czetsuya.demo;


import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.naming.NamingException;

 * @author Edward P. Legaspi
 * @since Nov 18, 2012
public class StartupListener {
 @Resource(name = "mailSession")
 private Session mailSession;

 private void init() throws NamingException, MessagingException,
   UnsupportedEncodingException {
  Message msg = new MimeMessage(mailSession);
  msg.setSubject("Hello World!");
  msg.setRecipient(RecipientType.TO, new InternetAddress(
    "", "czetsuya 2"));
  msg.setFrom(new InternetAddress("", "czetsuya 1"));

  BodyPart messageBodyPart = new MimeBodyPart();
  messageBodyPart.setText("Hello World!.");

  Multipart multipart = new MimeMultipart();


How to send an email in Glassfish using JavaMail session injection How to send an email in Glassfish using JavaMail session injection Reviewed by Edward Legaspi on Sunday, November 18, 2012 Rating: 5

No comments:

Powered by Blogger.