Spring Mail Sending Email with Freemarker HTML Template Example

摘要: In this tutorial we demonstrate how to send a HTML email using a custom freemarker template using spring framework. In this topic we learn how to create and configure a custom freemarker template using spring.

In this tutorial we demonstrate how to send a HTML email using a custom freemarker template using spring framework. In this topic we learn how to create and configure a custom freemarker template using spring.

Project Structure

Let’s start by looking at our project structure.

Maven Dependencies

We use Apache Maven to manage our project dependencies. Make sure the following dependencies reside on your class-path.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

    <name>Spring MAIL - ${project.artifactId}</name>





Email Configuration Properties

We can use two types of configuration files. Both files reside on the classpath located in the src/main/resources folder. The first and my favorite is application.yml file. I like this type because it has a better structure than the other and you’ll have to type less.

# application.yml

    default-encoding: UTF-8
    host: smtp.gmail.com
    username: [email protected]
    password: secret
    port: 587
          auth: true
            enable: true
    protocol: smtp
    test-connection: false

The second option you can use is the application.properties file.

# application.properties

[email protected]

Mail Object

We are using this Mail object to pass as an argument for our EmailService to encapsulate the details of an email message and content.

package com.memorynotfound.mail;

public class Mail {

    private String from;
    private String to;
    private String subject;
    private String content;

    public Mail() {

    public Mail(String from, String to, String subject, String content) {
        this.from = from;
        this.to = to;
        this.subject = subject;
        this.content = content;

    public String getFrom() {
        return from;

    public void setFrom(String from) {
        this.from = from;

    public String getTo() {
        return to;

    public void setTo(String to) {
        this.to = to;

    public String getSubject() {
        return subject;

    public void setSubject(String subject) {
        this.subject = subject;

    public String getContent() {
        return content;

    public void setContent(String content) {
        this.content = content;

    public String toString() {
        return "Mail{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", subject='" + subject + '\'' +
                ", content='" + content + '\'' +

Freemarker Template Java Configuration

We need to tell freemarker where the email templates are located. We do this by creating a FreeMarkerConfigurationFactoryBean and set the location using the setTemplateLoaderPath() method. This tells freemarker to look for a folder on the class-path named templates.

package com.memorynotfound.mail;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;

public class FreemarkerConfig {

    public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration() {
        FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
        return bean;

Freemarker HTML Email Template

Now it’s time to write the actual freemarker HTML email template. This file is located in the src/main/resources/templates folder. We create a very basic HTML email template. Notice, we are linking to an email attachment by using the cid: inside the src attribute inside the <img/> element. This image will be attached as an attachment in the email service.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <title>Sending Email with Freemarker HTML Template Example</title>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

    <link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>

    <!-- use the font -->
        body {
            font-family: 'Roboto', sans-serif;
            font-size: 48px;
<body style="margin: 0; padding: 0;">

    <table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border-collapse: collapse;">
            <td align="center" bgcolor="#78ab46" style="padding: 40px 0 30px 0;">
                <img src="cid:logo.png" alt="https://memorynotfound.com" style="display: block;" />
            <td bgcolor="#eaeaea" style="padding: 40px 30px 40px 30px;">
                <p>Dear ${name},</p>
                <p>Sending Email using Spring Boot with <b>FreeMarker template !!!</b></p>
            <td bgcolor="#777777" style="padding: 30px 30px 30px 30px;">


Populating HTML Email with Freemarker Template

First, we can create a MimeMessage using the JavaMailSender.createMimeMessage() method. Next, we create a MimeMessageHelper and pass in the MimeMessage as an argument. The MimeMessageHelper let’s us add attachments to the MimeMessage.

Then, we lookup the freemarker template using the Configuration.getTemplate() method. Finally, we process the template using the FreeMarkerTemplateUtils.processTemplateIntoString() method and pass in the template and a model. This model are key values which can be used inside the freemarker template.

package com.memorynotfound.mail;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class EmailService {

    private JavaMailSender emailSender;

    private Configuration freemarkerConfig;

    public void sendSimpleMessage(Mail mail) throws MessagingException, IOException, TemplateException {
        MimeMessage message = emailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,

        helper.addAttachment("logo.png", new ClassPathResource("memorynotfound-logo.png"));

        Template t = freemarkerConfig.getTemplate("email-template.ftl");
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(t, mail.getModel());

        helper.setText(html, true);



Spring Mail – Sending Email with Freemarker HTML Template Example

We are using Spring Boot to bootstrap our application. When the application is invoked we simply create a new Mail object and send it using our previously created EmailService

package com.memorynotfound.mail;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.HashMap;
import java.util.Map;

public class Application implements ApplicationRunner {

    private static Logger log = LoggerFactory.getLogger(Application.class);

    private EmailService emailService;

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);

    public void run(ApplicationArguments applicationArguments) throws Exception {
        log.info("Sending Email with Freemarker HTML Template Example");

        Mail mail = new Mail();
        mail.setFrom("[email protected]");
        mail.setTo("[email protected]");
        mail.setSubject("Sending Email with Freemarker HTML Template Example");

        Map model = new HashMap();
        model.put("name", "Memorynotfound.com");
        model.put("location", "Belgium");
        model.put("signature", "https://memorynotfound.com");


Example Received Email

If your configuration is correct, you should receive the following email in your inbox.


上一篇: Spring Mail Sending Email with Thymeleaf HTML Template Example
下一篇: Spring Mail Sending Email with Inline Attachment Example
 评论 ( What Do You Think )


  • 微信公众号

  • 我的微信


1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号