del.icio.us Digg DZone Reddit StumbleUpon
Send E-mail Using Spring and JavaMail - Willie Wheeler
« Previous | 1 | 2 | 3 | Next »

Alternative 2: Configuring JavaMail with JNDI

Server JNDI configuration (using Tomcat 6 as an example)

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):

Code listing: /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.

Spring configuration

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.

Social bookmarks: del.icio.us Digg DZone Reddit StumbleUpon
« Previous | 1 | 2 | 3 | Next »

Comments (19)

Hello Willie, are you ok?

I'm newbie in the Spring, and i like source-code this example. Do you send me? My address mail is andersonajx at gmail dot com

Thanks a lot.
By Anderson Clayton on May 15, 2008 at 6:56 AM PDT
Hi Anderson. I will shortly post an update (SAM 0.2) to the SAM application in the Downloads section of the site. That update will feature Spring/JavaMail code. The app is simple enough that even Spring newbies should be able to follow it, though let me know if you have questions.
By Willie Wheeler on May 24, 2008 at 6:25 AM PDT

OK, sam-0.2.zip is now available.

By Willie Wheeler on May 25, 2008 at 2:59 AM PDT
Thanks a lot. This was very helpful
By BISO on Jul 16, 2008 at 2:52 AM PDT
Can you please provide the URL to the source?
By san on Oct 9, 2008 at 3:59 AM PDT

Can you be more specific about JNDI? How to config mailSession bean?

By Mr.A on Oct 10, 2008 at 12:19 AM PDT

Is it something like this?

<bean id="mailSession"
    class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName">
        <value>java:comp/env/mail/Session</value>
    </property>
</bean>
By Mr.A on Oct 10, 2008 at 1:01 AM PDT

@san: Here it is.

@Mr.A: Yeah, either that, or else you can use the jee namespace config as well.

<jee:jndi-lookup id="mailSession"
    jndi-name="mail/Session" resource-ref="true"/>

Don't forget the namespace and schema location declaration at the top of the file if you decide to go with that. Also, you probably already know—but just in case not—you need to configure the resource on your app server (or servlet container) itself too.

If you don't want to mess around with all of that, you can just configure a MailSender instance directly in the app context config. You can use either the JavaMailSenderImpl, or else the CosMailSenderImpl if you're using Spring 2.0. It looks like they dropped support for CosMailSenderImpl in Spring 2.5.

By Willie Wheeler on Oct 10, 2008 at 1:09 AM PDT

Thanks.

I tried to use JNDI with JBoss, but failed. The error message is javax.naming.NameNotFoundException: mail not bound.

Do you have any suggestion?

By Mr.A on Oct 10, 2008 at 4:16 AM PDT

@san: You will need to consult the JBoss docs for that.

By Willie Wheeler on Oct 11, 2008 at 12:25 AM PDT
Great job, shows just how simple and straight forward Spring mail can be. Took about 20 minutes to get my app to work using your tutorial. Thanks for the help.

Mark
By Mark on Dec 4, 2008 at 11:46 PM PST

I am trying to send an email using Spring and GMail. However, the email is not getting sent. I'm not receiving any errors. Below is my setup:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com"/>
    <property name="port" value="25"/>
    <property name="username" value="MyUsername"/>
    <property name="password" value="MyPassword"/>
    <property name="javaMailProperties">
    <props>
        <prop key="mail.smtp.auth">true</prop>
        <prop key="mail.smtp.starttls.enable">true</prop>
    </props>
    </property>
</bean>

<bean id="userDefServiceTarget"
    class="com.xxx.setups.userdef.business.UserDefMgr" >
    <property name="mailSender"><ref local="mailSender"/></property>
</bean>

In my UserDefMgr class:

public void postMail()
{
    SimpleMailMessage message = new SimpleMailMessage() ;
    message.setSentDate(new Date()) ;
    message.setSubject("Test") ;
    message.setText("This is a test email.") ;
    message.setFrom("test@xx.com") ;
    mailSender.send(message) ;
}

What am I doing wrong? It's going thru the method and has all of the properties when it executes the send method.

Thanks.

By Sonny on Jan 4, 2009 at 10:39 AM PST

@Sonny: I haven't tried sending through a Gmail SMTP server, so I can't speak to the specifics there (such as whether they're using port 25 or some other port, etc.), but I would offer a couple of suggestions:

  1. Check out any docs they may have regarding using their SMTP servers, and in particular, the required client-side configuration. From the looks of it they want either port 465 or port 587, not the standard port 25. So that there may be your issue.
  2. Use Wireshark to look at the communication between your client and the Gmail SMTP server. Here is an article that explains how to do that:

    Wireshark in Fifteen Minutes

This will allow you to see whether you're actually hitting the SMTP server, what error messages it's sending, etc.

(Sorry about the completely gratuitous thumbnail image there; I'm testing out my new comment system.) :-)

By Willie Wheeler on Jan 4, 2009 at 10:30 PM PST

Hi Willie,

I found what I need in this article, but still one more info needed. Could you help me on how to configure JavaMail with JNDI in Glassfish? Thanks a lot.

Daniel

By Daniel on May 11, 2009 at 3:47 PM PDT

hi i am using springs and javamail to send email, how can i add another host name i need to add an exchage server , can u also mention where all i should be changin

By rams on Aug 21, 2009 at 3:25 AM PDT

I am not sure about Spring, but I saw this quick code example of sending mail with javamail API Check it out here: http://ehow-java.blogspot.com/2010/01/simple-mail-sender-example-with.html

By Cashyup on Jan 25, 2010 at 2:37 PM PST

Thanks. Wanted to check out the secure SMTP .

Regards, Franklin

By Franklin on Mar 8, 2010 at 1:14 AM PST

Hi,, Willie,, thanks,, greate site , greate article, I am a JEE developer, love writting code, i also like spring framework,, please keep it up,, even i have posted some article regarding java mail with spring in my site gananathsun.blogspot.com

By gananath on Mar 8, 2010 at 7:01 AM PST

Hi,

I am using JavaMailSender to send mails.The Mails are containing some unwanted header messages.How to avoid this?. In outlook web access if i open the mail subject,to and cc are empty how this informations are getting lost?

If any body can answer this it will be highly appriciated..

By Siva on Jun 11, 2010 at 9:59 AM PDT

Post a comment

Your name:
Your e-mail address (won't be displayed):
Your web site (optional):
example: www.xyz.com
Your comment:
Preview:
By You
Please help us reduce comment spam:
Spring in Practice
My brother and I are writing Spring in Practice for Manning!

What's New?

2009-08-30 - Check out my two-part series on DZone: Spring Integration: A Hands-On Tutorial.
2009-03-25 - My new article Getting Started with Spring Batch 2.0 is available on DZone.
Home | Consulting | Tech Articles | Mailing List | Contact | Spring Blog
Copyright © 2008 Wheeler Software, LLC.