Email with Spring and Velocity

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

Scenario

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:

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:

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:

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:

2.3. VelocityEngine

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

  • 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 the 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.

2.4. Beans configuration

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

  • 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

Summary

You’ve learned in this example how to compose html emails in Java with Spring and Velocity. All you need are 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.

If you liked this article, we would really appreciate a small contribution for our work! Donate now with Paypal.

Resources

Source code – GitHub repositories

Web

  1. Spring Email integration 
  2. Apache Velocity Project
Podcastpedia image
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.

About Adrian Matei

Creator of Podcastpedia.org and Codingpedia.org, computer science engineer, husband, father, curious and passionate about science, computers, software, education, economics, social equity, philosophy.