piątek, 18 października 2013

How to send mails from JBoss Wildfly (JavaMail & GMail)

It only takes a couple of minutes to configure Wildfly 8.0.0.Alpha4 server to send mails using your Google account.


  1. Turn on standalone WildFly instance

    ./<wild_fly_home>/bin/standalone.sh

  2. Add new Mail Session (assign JNDI name, you would like to use in your applications)



  3. When the session is created, click View and add some necessary properties like your username, password, SSL encryption etc

  4. Save changes and shut down Wildfly server (CTRL+C in terminal)
  5. Open standalone configuration file (<wild_fly_home>/standalone/configuration/standalone.xml) and replace lines:

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

    with

    <outbound-socket-binding name="mail-smtp">
      <remote-destination host="smtp.gmail.com" port="465"/>
    </outbound-socket-binding>
  6. Start Wildfly (look 1.)

How to send mail from Java EE?

Use this EJB as an example:
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.logging.Level;
import java.util.logging.Logger;

@Stateless
public class Mail {

    @Resource(name = "java:jboss/mail/gmail")
    private Session session;

    public void send(String addresses, String topic, String textMessage) {

        try {

            Message message = new MimeMessage(session);
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addresses));
            message.setSubject(topic);
            message.setText(textMessage);

            Transport.send(message);

        } catch (MessagingException e) {
            Logger.getLogger(Mail.class.getName()).log(Level.WARNING, "Cannot send mail", e);
        }
    }
}

Keep it simple!

4 komentarze:

  1. Making sense. May add to download Java Mail API. e.g.


    javax.mail
    javax.mail-api
    1.5.2

    OdpowiedzUsuń
  2. stanalone.xml was correct, restart, but
    mailserver always localhost:25
    I found a solution:

    // @Resource(lookup = "java:jboss/mail/gmail")
    private Session session;

    try {
    InitialContext ic = new InitialContext();
    session = (Session) ic.lookup("java:jboss/mail/gmail");
    Message message = new MimeMessage(session);....

    OdpowiedzUsuń