This tutorial will show you how to send a basic mail via Spring framework’s email support.

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. A class that comes in pretty handy when dealing with JavaMail messages is the org.springframework.mail.javamail.MimeMessageHelper class, which shields you from having to use the verbose JavaMail API. Using the MimeMessageHelper it is pretty easy to create a MimeMessage.

The code in the other email sending examples in this site explicitly created the content of the email message, using methods calls such as message.setText(..). This is fine for simple cases, and it is okay in the context of the aforementioned examples, where the intent was to show you the very basics of the API.
In typical enterprise application though, you are not going to create the content of your emails using the above approach for a number of reasons.

  • Creating HTML-based email content in Java code is tedious and error prone
  • There is no clear separation between display logic and business logic
  • Changing the display structure of the email content requires writing Java code, recompiling, redeploying…

Typically the approach taken to address these issues is to use a template library such as FreeMarker or Velocity to define the display structure of email content. This leaves your code tasked only with creating the data that is to be rendered in the email template and sending the email. It is definitely a best practice for when the content of your emails becomes even moderately complex, and with the Spring Framework’s support classes for FreeMarker and Velocity becomes quite easy to do. Find below an example of using the Velocity template library to create email content.

To use Velocity to create your email template(s), you will need to have the Velocity libraries available on your classpath. You will also need to create one or more Velocity templates for the email content that your application needs.

The following example shows you how to use the MimeMessageHelper to send an email using Velocity Engine.

For this tutorial we will create a standalone maven project in Eclipse. If you already have an idea on how to create a maven project in Eclipse will be great otherwise I will tell you here how to create a maven project in Eclipse.

The following configurations are required in order to run the application
Eclipse Mars
JDK 1.8
Have maven installed and configured
Spring and Java Mail dependencies in pom.xml
Now we will see the below steps how to create a maven based spring project in Eclipse
Step 1. Create a standalone maven project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

Now enter the required fields (Group Id, Artifact Id) as shown below
Group Id : com.roytuts
Artifact Id : springcore
Step 2. Modify the pom.xml file as shown below.

<project xmlns="" xmlns:xsi=""
        <!-- Velocity -->
        <!-- Spring framework -->
        <!-- Java Mail API -->
        <!-- junit -->

Step 3. If you see JRE System Library[J2SE-1.5] then change the version by below process

Do right-click on the project and go to Build -> Configure build path, under Libraries tab click on JRE System Library[J2SE-1.5], click on Edit button and select the appropriate jdk 1.8 from the next window. Click on Finish then Ok.

Step 4. Create src/main/resources folder for putting the resource files.

Do right-click on the project and go New -> Source Folder. Give Folder name: as src/main/resources and click on Finish button.

Step 5. Create an XML file email.xml under src/main/resources.

Do right-click on src/main/resources in the project and go New -> file. Give File name: as email.xml and click on Finish button.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    xmlns:xsi="" xmlns:p=""
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="" />
        <property name="port" value="121" />
        <property name="username" value="[email protected]" />
        <property name="password" value="******" />
        <property name="javaMailProperties">
                <!-- if you need ssl then uncomment below two lines -->
                <!-- <prop key=""></prop>
                <prop key="mail.smtp.starttls.enable">true</prop> -->
                <prop key="mail.smtp.auth">true</prop>
    <bean id="emailSender" class="">
        <property name="mailSender" ref="mailSender" />
        <property name="velocityEngine" ref="velocityEngine"/>
    <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="velocityProperties">

Step 6. Create Email Template email-template.vm under src/main/resources/velocity

        <h3>Hello ${user.userName}, welcome to the Velocity Email Template!</h3>
            Your email address is <a href="mailto:${user.emailAddress}">${user.emailAddress}</a>.

Step 7. Create a model class as shown below

package com.roytuts.springcore.model;
public class User {
    private String userName;
    private String emailAddress;
    public User(String userName, String emailAddress) {
        this.userName = userName;
        this.emailAddress = emailAddress;
    public String getUserName() {
        return userName;
    public void setUserName(String userName) {
        this.userName = userName;
    public String getEmailAddress() {
        return emailAddress;
    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;

Step 8. Create below EmailSender class under src/main/java folder

import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;
public class EmailSender {
    private JavaMailSender mailSender;
    private VelocityEngine velocityEngine;
    public void sendEmail(final String subject, final String message,
            final String emailAddress) {
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setFrom(new InternetAddress("[email protected]"));
                User user = new User("Gobinda", "[email protected]");
                Map<String, Object> userModel = new HashMap<String, Object>();
                userModel.put("user", user);
                String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                        "velocity/email-template.vm", userModel);
                message.setText(text, true);
        try {
            // mailSender.send(mailMessage);
            System.out.println("Email sending complete.");
        } catch (Exception e) {
    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    public void setVelocityEngine(VelocityEngine velocityEngine) {
        this.velocityEngine = velocityEngine;

Step 9. Create below Junit test class under src/test/java folder to test the application

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
public class EmailSenderTest {
    private EmailSender emailSender;
    public void setUp() throws Exception {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("email.xml");
        emailSender = applicationContext.getBean("emailSender", EmailSender.class);
    public void testSendEmail() {
        emailSender.sendEmail("How are you ?", "Hello Dear, How are you ?", "[email protected]");

Step 10. Now run the above Junit test class, you will see the below output in console

Console Output

Apr 24, 2016 12:49:43 PM prepareRefresh
INFO: Refreshing org[email protected]ccd017: startup date [Sun Apr 24 12:49:43 IST 2016]; root of context hierarchy
Apr 24, 2016 12:49:43 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [email.xml]
Email sending complete.

Step 11. Check the inbox you will get a message. If you do not find the message in inbox then check the Spam folder.
email spring velocity

See in the above image how email template using Velocity Engine has been used gracefully.
Thanks for reading.


Leave a Reply

Your email address will not be published. Required fields are marked *