Automated Email using Spring Framework and Velocity

This page describes the process one can take to send automated emails based on a velocity template, Maven and the Spring Framework. The page also covers how to send email with inline resources. These emails have the images included in the message as mime attachments.


  • Velocity Template Library
  • Spring Framework
  • Maven
  • SMTP port 25 access (eg. mail.yourhostname.com)

This page requires you have access to a mail server that can accept mail from your machine. You may typically test this by running telnet mail.yourhostname.com 25. Test this by manually sending a message and verify that it gets sent.

Start the project

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart

groupId: com.test
artifactId: test-email

Hit enter for the rest of the questions leaving them default.

After creating the project edit the pom.xml file and add the following dependencies.


Creating a template

The first step in the process is to create a email template. The template contains email layout. This is similar to creating a JSP page.

<h3>Hi ${user.userName}, welcome!</h3>

   Your email address is <a href="mailto:${user.emailAddress}">${user.emailAddress}</a>.


Since we are using the autowiring functionality of the spring framework we dont really need to explicitly define the beans in xml. Instead all we need are the next few lines.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

<!-- The following is used for the @Autowired and @Required, @Resource etc... -->
        <context:component-scan base-package="com.test"/>

   <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
      <property name="host" value="mail.hostname.com"/>

   <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
      <property name="velocityProperties">


Creating the application

The following is the code to a simple java main application that will call the method that sends out the email.

package com.test;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class App {
        private JavaMailSender mailSender;
        private VelocityEngine velocityEngine;

        public JavaMailSender getMailSender() {
                return mailSender;

        public void setMailSender(JavaMailSender mailSender) {
                this.mailSender = mailSender;

        public VelocityEngine getVelocityEngine() {
                return velocityEngine;

        public void setVelocityEngine(VelocityEngine velocityEngine) {
                this.velocityEngine = velocityEngine;

        public static void main(String[] args) {
                // initialize spring context
                ApplicationContext context = new ClassPathXmlApplicationContext(
                                new String[] { "applicationContext.xml" });
                App app = (App) context.getBean("app");
                // call the method

        public void testEmail() {
                final User user = new User();

                MimeMessagePreparator preparator = new MimeMessagePreparator() {
                        public void prepare(MimeMessage mimeMessage) throws Exception {
                                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                                message.setFrom("neeraj.verma@hostname.com"); // could be
                                // parameterized...
                                Map model = new HashMap();
                                model.put("user", user);
                                String text = VelocityEngineUtils.mergeTemplateIntoString(
                                                velocityEngine, "com/test/email-template.vm", model);
                                message.setText(text, true);


package com.test;

public class User {
        private String userName;
        private String 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;

Running the code

run the code by executing the following command.

mvn exec:java -Dexec.mainClass="com.test.App"

In-line resources using Velocity Templates.

Change template to include images

<h3>Hi ${user.userName}, welcome!</h3>

   Your email address is <a href="mailto:${user.emailAddress}">${user.emailAddress}</a>.
<img src="cid:identifier1234"/>

Convert to send multi-part messages

        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true); // multipart

Add the image(s)

Be careful with the order in which you add the resources. It may not work if it is not ordered “correctly”.

        FileSystemResource res = new FileSystemResource(new File(
        message.addInline("identifier1234", res);

This site is a collaborative effort! The complete text and sourcecode for this is available on GitHub. Corrections and enhancements are welcome, please make the change and submit a pull request in the comment area below.

2 Responses to “Automated Email using Spring Framework and Velocity”

  1. 2 Chandraprakash
    February 22, 2013 at 3:19 am

    Thanks for such a wonderful post.It makes my work easier.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 77 other followers

December 2009
« Nov   Jan »

Blog Stats

  • 847,163 hits

%d bloggers like this: