miyukiutada
Photo credit: miyukiutada
del.icio.us Digg DZone Reddit StumbleUpon
1 | 2 | 3 | Next »
Software Development

Send E-mail Using Spring and JavaMail

Learn how to send e-mail from your Spring application using JavaMail.

This brief tutorial will show how to send e-mail using Spring and JavaMail. JavaMail can handle e-mail storage as well, but here we're just worrying about sending e-mail.

I happen to be using Spring 2.5 but this ought to work for earlier versions of Spring as well (at least Spring 2.0 I think).

Let's jump right in. You can configure your JavaMail session either in Spring itself or with JNDI. We'll look at both alternatives.

Alternative 1: Configuring JavaMail with Spring

You may be operating in an environment where you don't have a JNDI enterprise naming context (ENC) available. Or you may have some reason not to use it even if you do have a JNDI ENC. For example, I've written a simple application monitor, and I'll be adding e-mail alerting shortly. This is a standalone app and so there's no JNDI ENC. No problem; I can just configure JavaMail in the Spring application context configuration as shown below.

<!-- Mail service -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="your.smtphost.com"/>
    <property name="port" value="25"/>
    <property name="username" value="yourusername"/>
    <property name="password" value="yourpassword"/>
    <property name="javaMailProperties">
        <props>
            <!-- Use SMTP-AUTH to authenticate to SMTP server -->
            <prop key="mail.smtp.auth">true</prop>
            <!-- Use TLS to encrypt communication with SMTP server -->
            <prop key="mail.smtp.starttls.enable">true</prop>
        </props>
    </property>
</bean>

This bean is, as its name suggests, a mail sender. It is basically a wrapper around JavaMail SMTP, and the configuration reflects that. In the example I'm showing how you would enable SMTP-AUTH (supports authentication to the SMTP server) and TLS (supports message encryption), assuming your SMTP server has those capabilities. For more information see my article SMTP and SMTP-AUTH.

IMPORTANT: You will need to inject mailSender into your mail-sending service bean.

So that's how to configure JavaMail from Spring. Now here's how to do the same thing with JNDI, which you may want to do if you're running in an environment with a JNDI ENC (like an app server or a servlet container).

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

Comments (17)

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

I opine that you have to be the most professional topic? referring to this topic or just about paper writer performer. And you must be employed by the essay writing service to create such of really good already written essay.

By Lisa21 on Jan 28, 2010 at 11:50 AM PST

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 Annotations RefCard
Check out the new DZone Spring Annotations Refcard by Craig Walls!

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.