About 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

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:

Spring mail dependencies

<dependency>
	<groupId>javax.mail</groupId>
	<artifactId>mail</artifactId>
	<version>1.4.7</version>
	<scope>provided</scope>
</dependency>
<dependency>
	<groupId>jaf</groupId>
	<artifactId>activation</artifactId>
	<version>1.0.2</version>
	<scope>provided</scope>	
</dependency>

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 -->
<dependency>
	<groupId>org.apache.velocity</groupId>
	<artifactId>velocity</artifactId>
	<version>1.7</version>
</dependency>
<dependency>
	<groupId>org.apache.velocity</groupId>
	<artifactId>velocity-tools</artifactId>
	<version>2.0</version>
</dependency>

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 {
    
    @Autowired
    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.setTo(configService.getValue("EMAIL_TO_SUGGEST_PODCAST"));
                     message.setBcc("adrianmatei@gmail.com");
                     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);
                  }
               };
               mailSender.send(preparator);            
    }
    
//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.setTo(configService.getValue("EMAIL_TO_SUGGEST_PODCAST"));
 message.setBcc("adrianmatei@gmail.com");
 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

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

</html>

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>          
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	<property name="session" ref="smtpSession" />
</bean>    
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
  <property name="velocityProperties">
	 <value>
	  resource.loader=class
	  class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
	 </value>
  </property>
</bean>   
<bean id="emailNotificationServiceSuggestPodcast" class="org.podcastpedia.web.suggestpodcast.EmailNotificationServiceImpl">
  <property name="mailSender" ref="mailSender"/>
  <property name="velocityEngine" ref="velocityEngine"/>
</bean>
  • 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 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.

Resources

Source code – GitHub repositories

Web

  1. Spring Email integration 
  2. Apache Velocity Project

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 two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

One Response to "How to compose html emails in Java with Spring and Velocity"

  1. Igor says:

    Nice and simple. Like it.

Leave a Reply


7 × seven =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close