Search code examples
javajakarta-eejakarta-mailmail-serverjames

How to use Authenticator subclass in a Java EE application with JavaMail


In Java SE its easy to support the authentication part with such code :

Session session = session.getInstance(props,new MyAuthenticator());

But in Java EE the session instance is not created by the application, but its supplied by JNDI injection by the application server in the application.

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

How to handle the authentication part here? What about the authenticationType argument in the @Resource annotation

@Resource(name = "mail/JMsession", authenticationType = AuthenticationType.APPLICATION)  

Solution

  • In Java EE you can use the @MailSessionDefinition annotation (or its equivalent in XML) to define the mail Session that you later on inject.

    Its user and password attributes are the declarative version of the programmatic Authenticator's PasswordAuthentication.

    @MailSessionDefinition is available on Java EE 7 servers, such as GlassFish 4 and also already in WildFly 8 (previously JBoss AS 8).