Questo sito è ancora in costruzione.
L'attuale sito ufficiale del JUG Padova è all'indirizzo www.jugpadova.it

Tomcat 5.5.20 and JavaMail Sessions

You’ll find an article in italian on the same topic in my personal blog.

In Tomcat you can define a JNDI Resource for a JavaMail session putting the following code in you Context definition:

<Resource name="mail/Session" auth="Container"
            type="javax.mail.Session"
            mail.smtp.host="localhost"/>

And in you web.xml:

<resource-ref>
  <res-ref-name>mail/Session</res-ref-name>
  <res-type>javax.mail.Session</res-type>
  <res-auth>Container</res-auth>
</resource-ref>

Then you can use it in you code:

Context initCtx = new InitialContext();
Session session =
    (Session) envCtx.lookup("java:comp/env/mail/Session");

Using Tomcat 5.5.20 (and 5.5.17, and 5.5.23…and maybe other versions) the last statement will produce a ClassNotFoundException: org.apache.naming.factory.MailSessionFactory. The cause is obviously that class is missing from the common/lib/naming-factory.jar distributed by Tomcat. I don’t know if it was a (repeated) problem in building Tomcat. Luckly the source code of that class is still present in the source distribution of Tomcat. Simply it isn’t included in the build process if you don’t have the JavaMail and the JavaBeans Activation Framework in the build classpath. So I re-built the naming-factory.jar file and substituted in common/lib.

You can rebuild your own JAR, or download my new naming-factory.jar.

I discovered this problem (bug?) installing LifeRay 4.1.2 using the WAR distribution. On the contrary the LifeRay-Tomcat bundle contains the correct naming-factory.jar yet. The LifeRay error in this case is more obscure. It reports a javax.naming.NameNotFoundException: Name mail is not bound in this Context! Of course the JNDI Resource is correctly configured. This happens because LifeRay try to guess the JNDI name of the resource, that changes for the different application servers. So that exception comes from one of the attempts, and the real problem is lost and hidden. So, if you’ll see a such message, don’t spend time re-re-re-configuring your JNDI resources…but patch Tomcat!