Email service configuration in Wildfly

Goal

Configuration of the email service in Wildfly

Description

This recipe will explain the basic steps one needs to do to configure the mail service in Wildfly (we’re using version 10.1).

Basically, we’ll need to configure the mail-session and the outbound-socket-binding in standalone.xml, as follows (we’re assuming you’ll use GMail to send the e-mail but the configuration to other mail servers should be similar), as shown in the next section.

How to

...
  <subsystem xmlns="urn:jboss:domain:mail:2.0">
    ...
    <mail-session name="myAppMailSession" jndi-name="java:jboss/mail/myapp">
      <smtp-server outbound-socket-binding-ref="gmail-smtp" ssl="true" username="someuser@gmail.com" password="somepassword" />
    </mail-session>
  <subsystem>
...
  <socket-binding-group name="standard-sockets" default-interface="public" port-offset="${jboss.socket.binding.port-offset:0}">
    ...
    <outbound-socket-binding name="gmail-smtp" source-port="0" fixed-source-port="false">
      <remote-destination host="smtp.gmail.com" port="465" />
    </outbound-socket-binding>
  </socket-binding-group>
...

And with the previous configuration, we are now allowed to create our implementation to leverage that service and send emails within our application. A possible implementation is shown next (you’ll need to make sure that you have a dependency on javax.mail.mail-api – provided, in case you’re using maven – in the project):

@Stateless
public class MailService {

  private static final Logger LOG = LoggerFactory.getLogger(MailService.class);

  // This must match the jndi-name property in the mail-session
  // configuration specified before
  @Resource(name = "java:jboss/mail/myapp")
  private Session session;

  public void send(final String addresses, final String subject, final String text) {
    try {
      final Message message = new MimeMessage(session);
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addresses));
      message.setSubject(subject);
      message.setText(text);

      Transport.send(message);
    } catch (MessagingException e) {
      LOG.error("Cannot send mail", e);
    }
  }
}

This may also be configured in the Wildfly console, as specified here, in case you prefer and you understand Portuguese.

Explanations

All explanations were made in place. Therefore, there’s nothing useful to add here, I suppose…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s