Thursday, 29 July 2010

Sending e-mails in Java with Spring – GMail SMTP server example


For e-mail sending in Java, the JavaMail API is the standard solution. As the official web page states, "The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications". The necessary classes are included in the JavaEE platform, but to use it in a standalone JavaSE application you will have to download the corresponding JAR from here.

Note: Unless you're using Java SE 6, you will also need the JavaBeans Activation Framework (JAF) extension that provides the javax.activation package. We suggest you use version 1.1.1 of JAF, the latest release. JAF is included with Java SE 6.

JavaMail can unfortunately be a little cumbersome and difficult to configure and use. In case you have embraced the Spring framework for your applications, you will be glad to find out that Spring provides a mail abstraction layer. As the reference documentation states, "The Spring Framework provides a helpful utility library for sending email that shields the user from the specifics of the underlying mailing system and is responsible for low level resource handling on behalf of the client." Great, let's see now how to leverage this library.

First, create a new Eclipse project named "SpringMailProject". In the project's classpath, make sure to include the following libraries (note that the 3.0.2.RELEASE Spring version was used):

  • mail.jar (the core JavaMail classes)
  • org.springframework.asm-3.0.2.RELEASE.jar
  • org.springframework.beans-3.0.2.RELEASE.jar
  • org.springframework.context.support-3.0.2.RELEASE.jar
  • org.springframework.core-3.0.2.RELEASE.jar
  • org.springframework.expression-3.0.2.RELEASE.jar
  • com.springsource.org.apache.commons.logging-1.1.1.jar

Note1: The commons-logging library from Apache is needed and was included in the classpath
Note2: You will also need the Java Activation Framework if you are using Java 1.5 or earlier

We will use MailSender, a Spring interface that defines a strategy for sending simple mails. Since this is just an interface, we need a concrete implementation and that comes in the form of JavaMailSenderImpl. This class supports both JavaMail MimeMessages and Spring SimpleMailMessages.

We will create a simple Spring service that will be used for sending mail. One method will create a SimpleMailMessage on the spot, while the other will use a preconfigured default message. The source code for the service is the following:

package com.javacodegeeks.spring.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

@Service("mailService")
public class MailService {
    
    @Autowired
    private MailSender mailSender;
    @Autowired
    private SimpleMailMessage alertMailMessage;
    
    public void sendMail(String from, String to, String subject, String body) {
        
        SimpleMailMessage message = new SimpleMailMessage();
         
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body);
        mailSender.send(message);
        
    }
    
    public void sendAlertMail(String alert) {
        
        SimpleMailMessage mailMessage = new SimpleMailMessage(alertMailMessage);
        mailMessage.setText(alert);
        mailSender.send(mailMessage);
        
    }
    
}

The class is just a POJO and its service name is "mailService", marked by the stereotype Service annotation. The beans wiring strategy used is the one of autowiring, thus the Autowired annotation is used. Note that the autowiring can be performed using both the name and the type of a bean.

The corresponding Spring XML file that bootstraps the container is the following:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
>

    <context:component-scan base-package="com.javacodegeeks.spring.mail" />    
    
    <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@gmail.com"/>
        <property name="password" value="mypassword"/>
        <property name="javaMailProperties">
            <props>
                <!-- Use SMTP transport protocol -->
                <prop key="mail.transport.protocol">smtp</prop>
                <!-- 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>
                <prop key="mail.debug">true</prop>
            </props>
        </property>
    </bean>
    
    <bean id="alertMailMessage" class="org.springframework.mail.SimpleMailMessage">
        <property name="from">            
            <value>myusername@gmail.com</value>
        </property>
        <property name="to">            
            <value>myusername@gmail.com</value>
        </property>
        <property name="subject" value="Alert - Exception occurred. Please investigate"/>
    </bean>
    
</beans>


This is a quite simple Spring config file. Some things to mention though:

  • The base package from which the context scanning will start is declared and is set to "com.javacodegeeks.spring.mail".
  • The "mailSender" bean is declared and a bunch of its properties are appropriately set (use your own SMTP server configuration attributes and credentials).
  • The "alertMailMessage" is a preconfigured Spring SimpleMailMessage and this will be injected in the "MailService" class using "by name autowiring".

In case you wish to use Gmail's SMTP server, make sure that the following JavaMail properties are configured appropriately:
host=smtp.gmail.com
port=25
username=your-gmail-username
password=your-gmail-password
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.starttls.enable=true

While in development phase, set "mail.debug" to true if you want the mail client to generate informative logs. However, remember to set this to false when in production, because the amount of logs could degrade the application's performance and/or fill-up your hard disks.

Finally, we create a class that will be used to create the Spring container and test the simple mail service we created. The source code is the following:

package com.javacodegeeks.spring.mail;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class MailServiceTest {

    public static void main(String[] args) {
        
        ApplicationContext context = new FileSystemXmlApplicationContext("conf/spring.xml");

        MailService mailService = (MailService) context.getBean("mailService");
        
        mailService.sendMail("myusername@gmail.com", "myusername@gmail.com", "Testing123", "Testing only \n\n Hello Spring Email Sender");
        
        mailService.sendAlertMail("Exception occurred");
        
    }
    
}

The FileSystemXmlApplicationContext class is used as the ApplicationContext. We pass the Spring's XML file location in the constructor and the class creates the container, instantiates the beans and takes care of the dependencies. Don't you love Spring? Next, we retrieve a reference of our "MailService" service using the "getBean" method and invoke the two methods.

That's all. As always, you can download the full Eclipse project from here.

Related Articles :

10 comments:

  1. Nice write up -
    I think lots of developers as well as beginners will find this very useful indeed.

    With Spring framework, sending email has never been easier.

    Thanks again for sharing.

    Helen Neely

    ReplyDelete
  2. nice :D i've just refactored my project to support spring mail :D and now using spring schedule (quartz) to schedule system to send email's log :D nice one

    ReplyDelete
  3. Thanks again, I just spent time over the weekend using the tips you highlighted here, and must say they are top class.

    I just tried them on a pet project I'm working on and it worked like a dream.

    Helen Neely

    ReplyDelete
  4. How about mail functionallity not as a service, but more object oriented with only a mail message object:

    @Configurable
    public class MailMessage {

    @Autowired
    private MailSender mailSender;

    private final SimpleMailMessage message;

    public MailMessage(String from) {
    message = new SimpleMailMessage();
    message.setFrom(from);
    }

    public MailMessage setReply(String replyTo) {
    message.setReplyTo(replyTo);
    return this;
    }

    public MailMessage setTo(String to) {
    message.setTo(to);
    return this;
    }

    public MailMessage setCc(String cc) {
    message.setCc(cc);
    return this;
    }

    public MailMessage setBcc(String bcc) {
    message.setBcc(bcc);
    return this;
    }

    public MailMessage setSubject(String subject) {
    message.setSubject(subject);
    return this;
    }

    public MailMessage setBody(String body) {
    message.setText(body);
    return this;
    }

    public void send() {
    mailSender.send(message);
    }
    }

    Now you can just code:
    MailMessage message = new MailMessage("abc.def@gmail.com").setTo("ghi.jkl@gmail.com").setSubject("Hello").setBody("Hello World!");
    message.send();

    ReplyDelete
  5. Hi Emiel,
    Very nice suggestion there!
    Thanks for your comment!

    ReplyDelete
  6. it gives me

    java.lang.NullPointerException
    at com.nvolve.email.model.MailMessage.send(MailMessage.java:52)
    at com.nvolve.user.service.UserManagerImpl.createUser(UserManagerImpl.java:129)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

    ReplyDelete
  7. Really nice article. Helped me alot.

    ReplyDelete
  8. One of the most important thing here is identifying/defining properties for JavaMailSenderImpl..., and rest will be taken care by Rod Johnson's code... :)

    ReplyDelete
  9. Great article and this was more useful and I was able to save my valuable time because of this.Thanks men.

    ReplyDelete
  10. Hi,
    I´ve got the following code up and running, see below:

    My question is, I am receiving emails on my gmail account but the from is always myself and not the person´s email address, even if I hardcode it in the implementation class as message.setFrom("somebody@hotmail.com"); still does not work. Any ideas?

    ...

    //implementation class:

    @Service("mailService")
    public class MailService {

    @Autowired
    private MailSender mailSender;
    @Autowired
    private SimpleMailMessage alertMailMessage;

    public void sendMail(String from, String to, String subject, String body) {

    SimpleMailMessage message = new SimpleMailMessage();

    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(body);
    mailSender.send(message);

    }
    ....
    //servlet-...xml








    smtp

    true

    true
    true

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...