Spring Boot Freemarker Email Template

This Spring Boot Freemarker Email Template tutorial walks you through sending the email with freemarker template using Spring Boot. This topic will cover, how to setup maven project, email service implementation, load freemarker template, Spring Boot application configuration.
If you are newbie on the Spring Boot and Freemaker, you may refer to the post Spring Boot FreeMarker Hello World Example before starting this topic.

Other interesting posts you may like

Let’s begin:

Project structure
In this Spring Boot Freemarker Email Template tutorial, we will create a project with directory structure like below

Spring Boot Freemarker Email Template

Maven Dependencies
To create Spring Boot Freemarker Email Template example, you need to add dependencies into pom.xml file like below:

Mail Service implementation
Our Mail service is implemented such as the below class

Dig deeper: The mail service is annotated as “mailService” using @Service annotation. Beside, we use @Autowired annotation to autowire JavaMailSender and free marker configuration beans.

Spring MimeMessageHelper class provides support for HTML text content, inline elements such as images, and typical mail attachments. It also takes care of populating MimeMessage object.

processTemplateIntoString() method replaces the placeholders values with model attribute values and populates email contents from FreeMarker template.

JavaMailSender.send() method to send populated MIME message.

Configuration properties

Fetch email properties into EmailProperties bean

Setup Mail sender
Create mail sender using Spring JavaMailSenderImpl class

Mail Pojo
This is simple pojo class which contains different email attributes like mailFrom, mailTo, mailCc, mailBcc, mailSubject, mailContent, contentType, attachments and model.

FreeMarker Email Template
Create freeMarker email template file (email-template.ftl) under folder /resources/templates/ along with respected placeholders variables.

Create Spring Boot Application
We create Spring Boot Application class which implements CommandLineRunner and has the main method

Run the Spring Boot Application
Foremost, we need to go to project directory in console, then package and run it using command line.

It sends email to specified recipients. Here is the email which i have received

That’s all on the Spring Boot Freemarker Email Template tutorial.
If you found this useful, please share it with your friends

References
Sending email

Download complete source code, click link below

spring-boot-freemarker-email-template-1.zip (21 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons