How to send Template based Email using Spring Boot and FreeMarker.

Hi all, In this Tutorial, i will be talking about template based Email using spring boot application.

To implement Email Functionality with spring boot We require below dependencies .

  1. FreeMarker (As we are going to use FreeMarker template for our Email Html and content)
  2. JavaMail Api(Api for sending java mails).

Whole source code can be found on my github repository

Lets first define and create Models, controller and other classes which we require to send email.

  1. EMail.java , A simple Pojo for having To,From,model and content to send mail.
  2. MailSender.java , A Service to send email
  3. emailtemplate.flth

First thing we have to define dependency of javamail, which we can do in spring boot using spring-boot-starter-mail. it defines all required dependencies for mail.

in pom.xml

<!-- send email -->         
<dependency>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>

in application.properties, We have to define email provider properties to send the mail. For Free Generic email provider we can use Gmail to send our mail.

spring.mail.host=smtp.gmail.com 
spring.mail.port=587
spring.mail.username=username
spring.mail.password=password
# Other properties
spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.connectiontimeout=5000 spring.mail.properties.mail.smtp.timeout=5000 spring.mail.properties.mail.smtp.writetimeout=5000 # TLS , port 587 spring.mail.properties.mail.smtp.starttls.enable=true

Sending normal text mail

import org.springframework.mail.SimpleMailMessage; 
import org.springframework.mail.javamail.JavaMailSender;
public class MailSender {
@Autowired
private JavaMailSender javaMailSender;

public void sendEmail(EMail mail) {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setTo(mail.getTo());
msg.setFrom(mail.getFrom());
msg.setSubject(mail.getSubject());
msg.setText(mail.getContent());
javaMailSender.send(msg);
}
}

Send an email with attachment

To send a mail with attachment, we have to create MimeMessage instead of simplemail message.

import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

public void sendEmailWithAttachment(EMail mail) throws MessagingException, IOException {
MimeMessage msg = javaMailSender.createMimeMessage();
// true = multipart message
MimeMessageHelper helper = new MimeMessageHelper(msg, true);

helper.setTo(mail.getTo());
helper.setFrom(mail.getFrom());
helper.setSubject(mail.getSubject());
helper.setText(mail.getContent());

// hard coded a file path
// FileSystemResource file = new FileSystemResource(new File("path/img.png"));
// helper.addAttachment("Google Photo",file);
helper.addAttachment("Google Photo", new ClassPathResource("img.png"));
javaMailSender.send(msg);
}

Mail with Freemarker template(Mail with Template)

import org.springframework.mail.SimpleMailMessage; 
import org.springframework.mail.javamail.JavaMailSender;
public class MailSender {
@Autowired
private JavaMailSender javaMailSender;
@Autowired
Configuration fmConfiguration;
public void sendEmail(EMail mail) {
MimeMessage mimeMessage =javaMailSender.createMimeMessage();
try {

MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

mimeMessageHelper.setSubject(mail.getMailSubject());
mimeMessageHelper.setFrom(mail.getMailFrom());
mimeMessageHelper.setTo(mail.getMailTo());
mail.setMailContent(geContentFromTemplate(mail.getModel()));
mimeMessageHelper.setText(mail.getMailContent(), true);

mailSender.send(mimeMessageHelper.getMimeMessage());
} catch (MessagingException e) {
e.printStackTrace();
}
}

public String geContentFromTemplate(Map < String, Object >model) {
StringBuffer content = new StringBuffer();

try {
content.append(FreeMarkerTemplateUtils.processTemplateIntoString(fmConfiguration.getTemplate("email-template.flth"), model));
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
}
}

Here we have created a method getContentFromTemplate. which is taking key-value pair and substitute the placeholders values with model attribute values and returns processed String, which we are setting in our mail content.

As freemarker looks templates in templates folder by default. so we can keep email-template.flth in /resources/templates folder.

<html>
<head></head>
<body>
<p>Dear ${firstName} ${lastName},</p>
<p>Sending Email using Spring 4 with <b>FreeMarker template !!!</b></p>
<p>Thanks</p>

</body>
</html>

We can create a Hashmap with keeping firstName and lastName as key and put their value. and it will be processed by FreeMarkerTemplateUtils
.processTemplateIntoString()
method.

Mail Pojo

package com.springlearning.model;

import java.util.Map;

public class EMail {
String to;
String from;
String subject;
String content;
private Map< String, Object > model;

public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
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 getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public Map<String, Object> getModel() {
return model;
}

public void setModel(Map<String, Object> model) {
this.model = model;
}
}

So Basically We used freemarker template, replaced the placeholders with value and used generated html as string into content. and send mail.

Angular,Vuejs,Android,Java,Git developer. i am nerd who want to learn new technologies, goes in depth.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store