Search code examples
jakarta-eeglassfish-3

Glassfish Email Configuration with Exchange


I have found quite a few references to configuring Glassfish for email, however I have not been able to solve my own issue and I am hoping that someone can help.

I have configured the JavaMail session in the Glassfish 3.12 console with the mailhost, user, sender address and description. Transport protocol is set to SMTP and I have added a mail.smtp.host (and mail.smtp.auth=false) property.

The code I am using to send mail is as follows:

public class JndiMail {
    @Resource(name = "mail/[my-email]")
    private Session mailSession;

    public void sendMessage() {
        Message msg = new MimeMessage(mailSession);
        try {
          msg.setSubject("[app] Email Alert");
          msg.setRecipient(RecipientType.TO,
            new InternetAddress("user@domain",
            "User name"));
          msg.setText("Hello ");
          Transport.send(msg);
        }
        catch(MessagingException me) {
          System.out.println(me.toString());
        }
        catch(UnsupportedEncodingException uee) {
        }
      }
}

Every time the application sends an email, I have a log message saying that the local host has rejected the email. I am trying to use a remote exchange server - not localhost. I don't understand why the remote email server is not being accessed? I realise that this should be fairly straight forward so I apologise if I have missed something.

These are the Glassfish logs:

[#|2013-03-26T10:00:39.334+1100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=29;_ThreadName=Thread-2;|DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]|#]

[#|2013-03-26T10:00:39.334+1100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=29;_ThreadName=Thread-2;|DEBUG SMTP: useEhlo true, useAuth false|#]

[#|2013-03-26T10:00:39.334+1100|INFO|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=29;_ThreadName=Thread-2;|DEBUG SMTP: trying to connect to host "localhost", port 25, isSSL false|#]

Solution

  • I have worked this out. The solution is fairly straight forward. When configuring the Javamail resource in Glassfish it is important to use the "mail/" prefix on the JNDI name. I had assumed that Glassfish added this. I found the solution by removing the injection from the above code and including the JNDI look up in the try catch:

    try {
        InitialContext ctx = new InitialContext();  
    Session session = (Session) ctx.lookup("mail/MyEmail"); 
     Message msg = new MimeMessage(session);