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

Creating an E-mail Template (Optional)

Sometimes the e-mail you want to send fits inside a standard template (e.g., maybe it always has the same sender, or maybe the same recipient, or whatever). You can define a template using Spring. Here's an example:

Code listing: Spring app context config file
<!-- Mail message -->
<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
    <property name="from">
        <value><![CDATA[Simple Application Monitor <noreply@somehost.com>]]></value>
    </property>
    <property name="to">
        <value><![CDATA[System Administrator <sysadmin@somehost.com>]]></value>
    </property>
    <property name="subject" value="SAM Alert"/>
</bean>

You can include as many e-mail templates in a Spring app context configuration, including none if you don't need a template. Here I've defined a template that specifies a "from" field, a "to" field and a "subject" field. It doesn't specify the date or the body. That template works say for an application monitoring system but it wouldn't work for an e-commerce site's order confirmation e-mail, which would need to have a variable "to" field.

IMPORTANT: I didn't show it above, but you will need to inject any e-mail templates (i.e. mail messages) you create into your mail-sending service bean. Otherwise the service bean has no way to use the template.

So that's that. Time for the Java code that actually sends the e-mail.

How to Send the E-mail from Your Service Bean

It turns out that the coding part is much simpler than the configuration (not that the config was too bad). Let's suppose for the sake of example that we want to send an e-mail based on the template that we defined above, and that you've injected that template into your service bean as mailMessage. Then here's the service bean code that allows you to use the template to send an e-mail:

Code listing: Your service bean
SimpleMailMessage message = new SimpleMailMessage(mailMessage);
message.setSentDate(new Date());
message.setText("Blah blah blah...");
mailSender.send(message);

You can see we're creating a new message based on the mailMessage e-mail template and mailSender that we injected into said service bean.

And that's it! Not too painful, right?

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

Comments (18)

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

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.