First you will need to expose a JavaMail session factory through JNDI in your server environment. This is environment-dependent, but let's look at an example.
Say you're using Tomcat 6. There are a couple things you must do.
First, move mail.jar and activation.jar to
your tomcat/lib directory. I say "move" rather than
"copy" because you will get an odd error if you leave the two JARs in
your application classpath. The error is
java.lang.IllegalArgumentException:
Cannot convert value of type [javax.mail.Session] to required type
[javax.mail.Session] for property 'session': no matching editors
or conversion strategy found
Second, define your Tomcat JNDI configuration, which might look
like this (e.g. in your context.xml file):
/META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/myapp" docBase="myapp" debug="5" crossContext="false">
<!-- JavaMail session factory -->
<Resource name="mail/Session"
auth="Container"
type="javax.mail.Session"
username="yourusername"
password="yourpassword"
mail.debug="true"
mail.user="yourusername"
mail.password="yourpassword"
mail.transport.protocol="smtp"
mail.smtp.host="your.smtphost.com"
mail.smtp.auth="true"
mail.smtp.port="25"
mail.smtp.starttls.enable="true"/>
</Context>
As with the non-JNDI example, I'm configuring for SMTP-AUTH and
TLS. If you are using SMTP-AUTH (authenticated SMTP sessions, which
you activate using mail.smtp.auth="true"), then you will
need to specify the username and password twice, as shown above.
Also, if your SMTP server supports it, you can tell JavaMail to
encrypt sessions using TLS by setting
mail.smtp.starttls.enable=true.
The above discussion applies only to Tomcat 6 (see Apache Tomcat 6.0 JNDI Resources HOWTO for detailed instructions); you'll need to consult your server docs to expose a JavaMail session factory through JNDI in your environment.
We still need to create a mail sender, but the configuration is
simpler since we did all the heavy lifting in context.xml
(or whatever, depending on your server environment). So for the
Spring application context, all we need is:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="session" ref="mailSession"/>
</bean>
IMPORTANT: As before, you will need to inject
mailSender into your mail-sending service bean.
So that takes care of configuring the mail sender, and also the JavaMail session factory if you are using JNDI. Let's visit one more topic before we dive into the code itself.