Apache Velocity Email Templates with Spring

We’re adding email services in NixMash Spring, with a new Mail Module and a Spring MVC Contact Form. Everything works great with emails that look like this.

That’s cool, but let’s spice things up and add some stylin’ to our Contact Emails, and for that we’ll use the Apache Velocity Java Templating engine. Velocity has been around for a while, but that doesn’t mean it’s not still awesome. What’s really nice about using Velocity in our scenario is that our Mail Module is a non-web application. We can create nice HTML emails without the overhead of Servlets, View Resolvers or Embedded Web Servers.

With Velocity our Contact Mail now looks like this.

Adding Apache Velocity to Our Mail Module

With Spring Boot, adding Velocity is really easy since it is partially baked-in to Spring. All we have to add is the VelocityEngine itself.

We begin by adding the Apache Velocity dependency in Gradle.

Generating the Message Body

We’re going to jump straight into our SendContactEmail() Service method where we’ll generate the HTML MimeMessage body content. The juicy code is half-way down in the try-catch{} statement. VelocityEngineUtils.mergeTemplate() is the current, non-deprecated way to create Velocity content (not the deprecated mergeTemplateString() which you often see.)

Note that VelocityEngineUtils() is in the Spring Framework, velocityEngine in the same line is from our Apache Velocity dependency. Also important to mention is that we don’t have to perform any configuration for the VelocityEngine Bean whatsoever, as Spring configures it for us. We simply declare it as a normal Bean in our MailServiceImpl() Class Constructor.

Configuring Velocity

By default Spring looks for Velocity templates in /resources/templates, like it does with Thymeleaf. We don’t want that but rather in /resources/velocity. We could do that in Java, but instead we’ll simply add the Resource Loader Path in our application.properties file. Check the Spring Common Application Properties Appendix for other Velocity property options.

The Template

Let’s look at the Velocity template. Since we’re not using a Servlet, and thus no Velocity View Resolver, we can’t employ Layout Templates and that sort of thing, but that’s hardly a restraint in populating our emails as you see below. Notice our header and footer template fragments, for instance.

And as we saw at the top, here is what this template produces as viewed in Thunderbird.

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.