January 30th, 2013

I found this a little tricky to do and not very well documented on the Tomcat manual and so here is a quick how-to based on what I have working.

Add a global resource to your server.xml

Some key points to notice here:

  • the attribute to set the password is password
  • all other attributes map to javax.mail property keys
  • you must set the mail.smtp.auth property
  <GlobalNamingResources>
    <Resource name="mail/Session"
              auth="Container"
              type="javax.mail.Session"
              mail.transport.protocol="smtp"
              mail.smtp.host="${mail.host}"
              mail.smtp.port="${mail.port}"
              mail.smtp.user="${mail.username}"
              mail.smtp.auth="true"
              password="${mail.password}"
    />
  </GlobalNamingResources>

Add a resource link to each of your context.xml files

One for each web-app.  Alternatively you can just add the resource definition above to each one

<Context>
  <ResourceLink
            name="mail/Session"
            global="mail/Session"
            type="javax.mail.Session" />
</Context>

Use the mail session in your code

Now you can just follow the example in the Tomcat documentation. As an alternative if you’re using Spring you can configure JDNI resources as beans.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/jee
        http://www.springframework.org/schema/jee/spring-jee-3.1.xsd>

    <jee:jndi-lookup id="mailSession" jndi-name="mail/Session"/>
</beans>