In this post, we will learn how to send email from the spring boot application. We will also learn how to add an image in the email body and attach a PDF file to it.

We will use the FreeMarker template as the mail body. FreeMarker is a template engine that generates dynamic HTML files by processing values passed from the application layer.

We will use:

  • Spring Boot version : 2.2.4.RELEASE
  • Java version : 1.8
  • Spring boot Web, FreeMarker, lombok and mail dependencies.
  • Postman to test the application.

Let us begin! 🙂

Create the Spring boot application

Create a Spring boot application with required dependencies. Add spring-boot-starter-web, spring-boot-starter-freemarker, lombok and spring-boot-starter-mail dependencies.

The complete pom.xml file is given below.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""
		<relativePath/> <!-- lookup parent from repository -->
	<description>Demo project for Spring Boot</description>





Add mail related configurations

Add the below spring configuration properties to the ‘’ configuration file.

spring.mail.username=your mailid
spring.mail.password=your password

Few of the used configuration properties are:

  • spring.mail.protocol: The protocol used for sending the mail.
  • We are using Gmail as SMTP host in this example.
  • spring.mail.username: SMTP server login username. Replace with your Gmail Id.
  • spring.mail.password: SMTP server password. Enter your Gmail password here.
  •*: Other Java mail properties.

Create an configuration file and define a FreeMarker template configuration bean. Here, we are setting the template file path. This template file is used as the email body.

package com.asb.example.config;

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

public class EmailConfig {

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

Create a email request DTO

Create an DTO class. This class is used as the request object to send the email.

package com.asb.example.dto;

import lombok.Getter;
import lombok.Setter;

public class EmailRequestDto {

	private String from;
	private String to;
	private String subject;
	private String name;

Create a email service

Create a spring service class called This class will process the FreeMarker template file and create an email body and send the request to the SMTP server.

package com.asb.example.service;

import java.nio.charset.StandardCharsets;
import java.util.Map;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import com.asb.example.dto.EmailRequestDto;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class MailService {

	private JavaMailSender mailSender;

	private Configuration configuration;

	public String sendMail(EmailRequestDto request, Map<String, String> model) {

		String response;
		MimeMessage message = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,;

			ClassPathResource pdf = new ClassPathResource("static/attachment.pdf");
			ClassPathResource image = new ClassPathResource("static/asbnotebook.png");
			Template template = configuration.getTemplate("email.ftl");
			String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

			helper.setText(html, true);
			helper.addInline("asbnotebook", image);
			helper.addAttachment("attachment.pdf", pdf);

			response = "Email has been sent to :" + request.getTo();
		} catch (MessagingException | IOException | TemplateException e) {
			response = "Email send failure to :" + request.getTo();
		return response;

We have the method sendMail() that accepts email requests and a map as the input parameter.

Spring provides a JavaMailSender class that can be used to send the email. We can auto wire this bean into our service, as shown in the above service class.

We have created a MimeMessage instance and created a MimeMessageHelper instance. This helper class can be used to set different email properties such as to, from, email text, attachments, etc.

We have used the addInline() method to embed the image to the email body. We have attached a PDF file with the help of the addAttachment() method of MimeMessageHelper.

The FreeMarker template is processed and converted into HTML text using Configuration instance. The FreeMarkerTemplateUtils class helps dynamically processing the FreeMarker template and generates the final HTML format. These two classes are available in the spring-boot-starter-freemarker library.

Expose a REST endpoint to send the email

Create a class. This is a RESTful controller with one POST method, that sends the email to the given email id with the subject.

package com.asb.example.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.asb.example.dto.EmailRequestDto;
import com.asb.example.service.MailService;

public class MailSenderController {

	private MailService mailService;

	public ResponseEntity<String> sendMail(@RequestBody EmailRequestDto emailRequest) {
		Map<String, String> model = new HashMap<>();
		model.put("name", emailRequest.getName());
		model.put("value", "Welcome to ASB Notebook!!");
		String response = mailService.sendMail(emailRequest, model);
		return new ResponseEntity<>(response, HttpStatus.OK);

Here, we are adding the ‘name’ and ‘value‘ into a map. These values are used by the FreeMarker template file.

Add the email template file

Create a FreeMarker template file called email.ftl under resources/template/ directory.

This template file contains a Header, a greeting with the name of the mail recipient, a greeting message and an image within the email body.

<html lang="en">
    <meta charset="utf-8">
    <title>Spring boot send mail example</title>
    <h2>Sending mail from Spring boot!!</h2>
    <h3>Hi ${name}!!</h3>
		<a href="">
			<img src='cid:asbnotebook' alt="ASBNotebook" style="width:10%"/>
			<p>ASB Notebook</p>

Make sure to add the image and PDF file under resources/static/ directory, as shown below.

spring boot email with image and attachment

Testing the application

Start the Spring boot application and send an email request, as shown below.

We are passing the email recipient, email subject, email from, and the email recipient name in this request.

Spring boot email with freemarker

We should get a confirmation message if the email is sent successfully.

If you face issues related to authentication, make sure that the below setting is enabled for your Gmail account.

Spring boot email example.

The below image displays the email received by the recipient.

We can observe the dynamically generated HTML content, embedded image, and the PDF file attachment.

Spring boot email example


In this post, we learned how to send an email by using the Spring boot application. We have also learned how to use the FreeMarker template as the mail body and embedding the image inside the email.

We also added a PDF file as an email attachment.

If you have enjoyed this post, please subscribe to the mailing list to get the latest posts in your mailbox. 🙂

Success! You're on the list.

Example code is available on GitHub. Happy coding! 🙂

You may also interested in