JavaScript is required!
You cannot use this page without JavaScript.

Using JavaMail API Part 2: Configuring JavaMail Session in GlassFish Server

Weblog | Using JavaMail API Part 2: Configuring JavaMail Session in GlassFish Server | Published: October 12, 2021 12:11:25

In this article, I discuss how to create a Mail Session in the GlassFish Administration Console which allows server-side components and applications to access JavaMail services with JNDI, using the Session properties you assign for them. JNDI (Java Naming and Directory Interface) is an API for locating application resources and components such as JavaMail Sessions, data sources, etc. in a distributed application.

In JavaEE8, we use the annotation @Resource found under the javax.annotation package to inject the pre-configured JavaMail Session into our JavaBean. The @Resource annotation enables GlassFish server to hide all the details of setting Mail Session properties and authenticating. Another benefit is that GlassFish server creates a single Session object and makes it available via JNDI to any component that needs it. The annotation's name attribute specifies mail/MySession — the JNDI name as specified in the section below.

Creating a JavaMail Session in GlassFish Server

To create a JavaMail session using the Admin Console, in NetBeans IDE, Click the Services tab. Expand the Servers node. Right-click the GlassFish Server instance and select View Admin Console. Alternatively, access it via http://localhost:4848/common/index.jsf. Ensure GlassFish Server is running. Then follow instructions in this link: Creating a JavaMail Session

Additional JavaMail Session Properties

At the bottom of the same page (Additional Properties), you need to add some important properties if for example you would like to use SMTP authentication. These are as follows:

mail.smtp.auth : true
mail.smtp.port : 587
mail.smtp.password : YourPassword

Save the configuration. Note: If you’re using say Gmail’s SMTP servers, you may need an extra SMTP TLS or SSL configuration like so:
mail-smtp-starttls-enable : true

Now go back to your code and inject the Session object into your JavaBean.

Injecting configured JavaMail Session into a JavaBean using @Resource annotation

We use the @Resource annotation to declare a reference to our configured Session resource. In this case, we decorate a field like this:

@Resource( name="mail/MySession" )
private Session session;

Now remove in your code the Session instantiation code, authentication code if any and all properties setting details and you’re good to go! You can override the JavaMail session properties in code if necessary. For example:

Properties props = session.getProperties();
props.put("mail.from", "user2@mailserver.com");

Note: You can also configure a JavaMail Session resource in Glassfish server using the asadmin utility or using the glassfish-resources.xml deployment descriptor file. I hope this was helpful.