JBoss mail service configuration

jboss mail configurationIn this simple tutorial we will show how to use the Java Mail service from WildFly - JBoss AS, either connecting to a local SMTP server or using Google SMTP server.

Let's start configuring JBoss Mail service on WildFly 8, then we will see how to configure the service on older application server versions (AS7 - AS5)

WildFly 8 Mail service configuration

WildFly mail subsystem is contained in all server configurations and exposes a Mail service bound at the JNDI name "java:jboss/mail/Default":


<subsystem xmlns="urn:jboss:domain:mail:2.0">
   <mail-session name="default" jndi-name="java:jboss/mail/Default">
        <smtp-server outbound-socket-binding-ref="mail-smtp" />
   </mail-session>
</subsystem>

The Mail Session in turn references an smtp host bound at localhost at port 25:

<outbound-socket-binding name="mail-smtp">
   <remote-destination host="localhost" port="25"/>
</outbound-socket-binding>

In order to configure the connection towards a pop/smtp server we need to set up username and password in the mail-session stanza and, if necessary, enable ssl. The following CLI scripts can be used to connect to GMail SMTP server using an example account (adjust user and password accordingly):

/subsystem=mail/mail-session=default/server=smtp/:write-attribute(name=username,This email address is being protected from spambots. You need JavaScript enabled to view it.">value=This email address is being protected from spambots. You need JavaScript enabled to view it.)
/subsystem=mail/mail-session=default/server=smtp/:write-attribute(name=password,value=mypassword)
/subsystem=mail/mail-session=default/server=smtp/:write-attribute(name=ssl,value=true)
/subsystem=mail/mail-session=default/:write-attribute(name=from,This email address is being protected from spambots. You need JavaScript enabled to view it.">value=This email address is being protected from spambots. You need JavaScript enabled to view it.)

Done with the mail session configuration, we will now set the outbound sockets, by setting host and port to GMail's defaults:

/socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=mail-smtp/:write-attribute(name=host,value=smtp.gmail.com)

/socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=mail-smtp/:write-attribute(name=port,value=465)

See in the next sections of this article for the SendMail Servlet which can be used to send a mail message using the Mail Session bound at "java:jboss/mail/Default". After my first attempt, the console log traced the following error:

javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted.

The reason for that is that you need to generate an application specific password instead of your original password. You can generate one at the link "https://accounts.google.com/IssuedAuthSubTokens" and use the generated application specific password in place your original password.

JBoss AS 7/JBoss EAP 6 configuration:

JBoss AS 7/EAP 6 configuration is slightly different as the authentication section is included in a <login> subelement which contains the username and password as follows:

 <subsystem xmlns="urn:jboss:domain:mail:1.0">
     <mail-session jndi-name="java:jboss/mail/Default">
          <smtp-server outbound-socket-binding-ref="mail-smtp">
               <login name="fmarchioni" password="fmarchioni"/>
         </smtp-server>
     </mail-session>
 </subsystem>

A more complex AS 7/EAP 6 configuration

Here's a more complex configuration which sets some more properties, such as the from field of the mail, a pop3-server authenticated socket connection, and e remote mail server destination. 


<subsystem xmlns="urn:jboss:domain:mail:1.0">
   <mail-session jndi-name="baseModule/EmailNotification" from="emailaddress.com">

      <smtp-server outbound-socket-binding-ref="mail-smtp">
            <login name="user" password="password" />
      </smtp-server>
      <pop3-server outbound-socket-binding-ref="mail-pop3">
             <login name="user" password="password" />
      </pop3-server>
   </mail-session>
  </subsystem>

. . . .

<outbound-socket-binding name="mail-smtp">
            <remote-destination host="remotehost" port="25"/>
</outbound-socket-binding>

<outbound-socket-binding name="mail-pop3">
            <remote-destination host="remotehost" port="25"/>
</outbound-socket-binding>

Now let's configure a mail server which will deliver our mails. You can try Apache James which is an opensource mail server, pretty light and simple to get started with it. Download it. Next unzip it and launch the run script which will start the mail server.

At startup James server just contains an administrative root account, so we will use this to add an user account. Unfortunately James does not provide (as far as I know!) a GUI interface to add users, to do that, telnet to localhost on port 4555 with the command:

telnet localhost 4555

You can log in with the root user name and password. After the login, we'll add an user. The adduser command expects a username and password combination. After adding users, you can use the listusers command to verify the entries and then exit the remote manager by typing quit. The whole session should look like this:
jboss mail service jboss mail service
Now let's create a simple Servlet which uses the Java Mail session to send a mail:

package com.sample;
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.Address;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.annotation.Resource;

@WebServlet(value="/mail")
public class SendMail extends HttpServlet
{
    @Resource(mappedName="java:jboss/mail/Default")
    private Session mailSession;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        {

            PrintWriter out=response.getWriter();
            try    {
                MimeMessage m = new MimeMessage(mailSession);
                Address from = new InternetAddress("senderemailaddress.com");
                Address[] to = new InternetAddress[] {new InternetAddress("receiveremailaddress.com") };

                m.setFrom(from);
                m.setRecipients(Message.RecipientType.TO, to);
                m.setSubject("JBoss AS 7 Mail");
                m.setSentDate(new java.util.Date());
                m.setContent("Mail sent from JBoss AS 7","text/plain");
                Transport.send(m);
                out.println("Mail sent!");
            }
            catch (javax.mail.MessagingException e)
            {
                e.printStackTrace();
                out.println("Error in Sending Mail: "+e);
            }
        }
    }
}

As you can see this Servlet injects the Java Mail Session using the Java EE @Resource annotation:
@Resource(mappedName="java:jboss/mail/Default")
private Session mailSession;

Fairly simple. Now test your servlet before moving to the next section.

Sending mail from AS 7 to a Remote GMail server

You can slighty change your configuration to use your GMail server account. The only tricky part of it is that it requires enabling the TLS/SSL transport, otherwise the GMail server will refuse to accept your connection.
In earlier JBoss AS version, you needed to set the mail.smtp.starttls.enable to true, in order to enable secure connection.
When using JBoss AS 7, you need to set the ssl property of the smtp server element. Here's a sample configuration:

<mail-session jndi-name="java:jboss/mail/Default">
    <smtp-server ssl="true" outbound-socket-binding-ref="mail-smtp">
                 <login name="yourusergmail.com" password="password"/>
    </smtp-server>
</mail-session>
. . . .
<outbound-socket-binding name="mail-smtp">
    <remote-destination host="smtp.gmail.com" port="465"/>
</outbound-socket-binding>

JBoss AS 5/6 Mail configuration

In earlier releases of JBoss application server, you can configure the Java Mail service by dropping a mail-service.xml into the deploy folder. Here's a sample configuration which uses an unauthenticated session:

<server>
  <mbean code="org.jboss.mail.MailService"
         name="jboss:service=Mail">
    <attribute name="JNDIName">java:/Mail</attribute>
    ...
    <attribute name="Configuration">
      <configuration>
        ...
        <property name="mail.smtp.host" value="localhost"/>
        <property name="mail.smtp.port" value="25"/>
        ...
      </configuration>
    </attribute>
    ...
  </mbean>
</server>

Adding support for user authentication:

You can follow the procedure we have exposed for AS 7 to create an user on your James server: the configuration would change to:

<server>
  <mbean code="org.jboss.mail.MailService"
         name="jboss:service=Mail">
    ...
       <attribute name="User">fmarchioni</attribute>
        <attribute name="Password">fmarchioni</attribute>   

        <attribute name="JNDIName">java:/Mail</attribute>
        <attribute name="Configuration">
      <configuration>
        ...

        <property name="mail.smtp.host" value="localhost"/>
         <property name="mail.smtp.port" value="25"/>

        <property name="mail.smtp.auth" value="true"/>
        <property name="mail.smtp.user" value="fmarchioni"/>
        ...
      </configuration>
    </attribute>
    ...
  </mbean>
</server>

Adding support for SSL/TSL:

Finally, if you want to enable SSL/TSL transport (as for GMail accounts) just add the following MBean configuration:

<server>
   <mbean code="org.jboss.mail.MailService"
          name="jboss:service=Mail">
     ...
     <attribute name="User">fmarchioni</attribute>
     <attribute name="Password">fmarchioni</attribute>

    <attribute name="JNDIName">java:/Mail</attribute>
     <attribute name="Configuration">
       <configuration>
         ...

        <property name="mail.smtp.host" value="smtp.gmail.com"/>

        <property name="mail.smtp.auth" value="true"/>
        <property name="mail.smtp.port" value="465"/>
        <property name="mail.smtp.starttls.enable" value="true"/>
        <property name="mail.smtp.socketFactory.class" value="javax.net.ssl.SSLSocketFactory"/>
        ...
      </configuration>
    </attribute>
    ...
  </mbean>
</server>

Related articles available on mastertheboss.com

JBoss MBeans POJO

JMX MBean services are the core building blocks of the JBoss Appl

How to a dump of JNDI tree with JMX console ?

#2 JBoss Howto. This is the recipe of the day

How to configure JBoss to bind to a different IP ?

  If you want to change the jboss.bind.address property use the 

How to shut down JBoss from remote ?

JBoss recipe of the day

How to create multiple instances of an Mbean?

  Supposing you need two instances of an MBean, let's say one fo

JBoss classloader issues

By default JBoss (prior to version 3.2) uses a flat class loading

Follow us on Twitter