Home » Java » Enterprise Java » How to compose html emails in Java with Spring and Velocity

About Adrian Matei

Adrian Matei
Adrian Matei (ama [AT] codingpedia DOT org) is the founder of Podcastpedia.org and Codingpedia.org, computer science engineer, husband, father, curious and passionate about science, computers, software, education, economics, social equity, philosophy.

How to compose html emails in Java with Spring and Velocity

In this post I will present how you can format and send automatic emails with Spring and Velocity. Spring offers alone the capability to create simple text emails, which is fine for simple cases, but in typical enterprise application you wouldn’t want to do that 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 requires writing Java code, recompiling, redeploying etc

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. For Podcastpedia I chose Velocity, which is a free open source Java-based templating engine from Apache. In the end my only coding task will be to create the data that is to be rendered in the email template and sending the email.

I will base the demonstration on a real scenario from Podcastpedia.org


On Podcastpedia.org’s Submit podcast page, we encourage our visitors and podcast producers to submit their podcasts to be included in our podcast directory. Once a podcast is submitted, an automatic email will be generated to notify me (adrianmatei [AT] gmail DOT com ) and the Podcastpedia personnel ( contact [AT] podcastpedia DOT org) about it.

Let’s see now how Spring and Velocity play together:

1. Prerequisites

1.1. Spring setup

“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.”[1]

1.1.1. Library depedencies

The following additional jars need to be on the classpath of your application in order to be able to use the Spring Framework’s email library.

  • The JavaMail mail.jar library
  • The JAF activation.jar library

I load these dependencies with Maven, so here’s the configuration snippet from the pom.xml:

Spring mail dependencies


1.2. Velocity setup

To use Velocity to create your email template(s), you will need to have the Velocity libraries available on your classpath in the first place.

With Maven you have the following dependencies in the pom.xml file:

Velocity dependencies in Maven

<!-- velocity -->

2. Email notification service

I defined the EmailNotificationService interface for email notification after a successful podcast submission. It has just one operation, namely to notify the Podcastpedia personnel about the proposed podcast.

The code bellow presents the EmailNotificationServiceImpl, which is the implementation of the interface mentioned above:

Java code to send notification email

package org.podcastpedia.web.suggestpodcast;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.velocity.app.VelocityEngine;
import org.podcastpedia.common.util.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;
public class EmailNotificationServiceImpl implements EmailNotificationService {
    private ConfigService configService;    
    private JavaMailSender mailSender;
    private VelocityEngine velocityEngine;
    public void sendSuggestPodcastNotification(final SuggestedPodcast suggestedPodcast) {
          MimeMessagePreparator preparator = new MimeMessagePreparator() {
                @SuppressWarnings({ "rawtypes", "unchecked" })
                public void prepare(MimeMessage mimeMessage) throws Exception {
                     MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                     message.setFrom(new InternetAddress(suggestedPodcast.getEmail()) );
                     message.setSubject("New suggested podcast");
                     message.setSentDate(new Date());
                     Map model = new HashMap();                 
                     model.put("newMessage", suggestedPodcast);
                     String text = VelocityEngineUtils.mergeTemplateIntoString(
                        velocityEngine, "velocity/suggestPodcastNotificationMessage.vm", "UTF-8", model);
                     message.setText(text, true);
//getters and setters omitted for brevity

Let’s go a little bit through the code now:

2.1. JavaMailSender and MimeMessagePreparator

The org.springframework.mail package is the root level package for the Spring Framework’s email support. The central interface for sending emails is the MailSender interface, but we are using the org.springframework.mail.javamail.JavaMailSender   interface (lines 22, 42), which adds specialized JavaMail features such as MIME message support to the MailSender interface (from which it inherits). JavaMailSender also provides a callback interface for preparation of JavaMail MIME messages, called org.springframework.mail.javamail.MimeMessagePreparator (lines 26-42)

2.2. MimeMessageHelper

Another helpful class when dealing with JavaMail messages is the org.springframework.mail.javamail.MimeMessageHelper class, which shields you from having to use the verbose JavaMail API. As you can see by using the MimeMessageHelper, it becomes pretty easy to create a MimeMessage:

Usage of MimeMessageHelper

 MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
 message.setFrom(new InternetAddress(suggestedPodcast.getEmail()) );
 message.setSubject("New suggested podcast");
 message.setSentDate(new Date());

2.3. VelocityEngine

The next thing to note is how the email text is being created:

Create email text with Velocity template

Map model = new HashMap();	             
model.put("newPodcast", suggestedPodcast);		             
String text = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "velocity/suggestPodcastNotificationMessage.vm", "UTF-8", model);
message.setText(text, true);
  • the VelocityEngineUtils.mergeTemplateIntoString method merges the specified template (suggestPodcastNotificationMessage.vm present in the velocity folder from the classpath) with the given model (model – “newPodcast”), which a map containing model names as keys and model objects as values.
  • you also need to specify the velocityEngine you work with
  • and, finally, the result is returned as a string

2.3.1. Create velocity template

You can see below the Velocity template that is being used in this example. Note that it is HTML-based, and since it is plain text it can be created using your favorite HTML or text editor.

Velocity template

		<h3>Hi Adrian, you have a new suggested podcast!</h3>
			From - ${newMessage.name} / ${newMessage.email} 
			Podcast metadataline 
			With the message


2.4. Beans configuration

Let’s see how everything is configured in the application context:

Email service configuration

<!-- ********************************* email service configuration ******************************* -->
<bean id="smtpSession" class="org.springframework.jndi.JndiObjectFactoryBean">
	<property name="jndiName" value="java:comp/env/mail/Session"/>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	<property name="session" ref="smtpSession" />
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
  <property name="velocityProperties">
<bean id="emailNotificationServiceSuggestPodcast" class="org.podcastpedia.web.suggestpodcast.EmailNotificationServiceImpl">
  <property name="mailSender" ref="mailSender"/>
  <property name="velocityEngine" ref="velocityEngine"/>
  • the JavaMailSender has a JNDI reference to a smtp session. A generic example how to configure an email session with a google account can be found in the Jetty9-gmail-account.xml file
  • the VelocityEngineFactoryBean is a factory that configures the VelocityEngine and provides it as a bean reference.
  • the ClasspathResourceLoader is a simple loader that will load templates from the classpath


You’ve learned in this example how to compose html emails in Java with Spring and Velocity. All you need is mail, spring and velocity libraries, compose your email template and use those simple Spring helper classes to add metadata to the email and send it.


Source code – GitHub repositories


  1. Spring Email integration 
  2. Apache Velocity Project
(0 rating, 0 votes)
You need to be a registered member to rate this.
1 Comment Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Igor Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

newest oldest most voted
Notify of

Nice and simple. Like it.