Sending HTML template based email in spring boot using free marker
Posted By : Gaurav Kumar | 04-Jan-2021
Hello Geeks, hope you all are doing well these days. Recently i was working in my project where a case came, where I had to send an email with attachment in specific format(basically template based).
So, after doing a quick research I came up with solution, In this particular blog post I am going to share the spring boot plugin i.e. free marker, to send template based multi lingual email.
So, first things first. Initiate a blank spring boot application with some of dependencies listed below:
1. web dependencies
2. jackson dependencies
3. lombok dependencies
4. mail dependencies
5. free marker dependencies
Also Read: Upgrading Spring Boot To The 2.3.4 Release
Here is the effective pom.xml, you can also use Gradle instead of Maven.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.techreloded</groupId>
<artifactId>spring-boot-email-freemarker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-email-freemarker</name>
<description>Trigger an email using spring boot freemarker</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.4.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Also Read: Spring Boot Application With Zull API Gateway
Now, add some properties into your application.properties or application.yml file I am stick with application.properties file.
application.properties
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.gmail.com
spring.mail.username=your-gmail-id
spring.mail.password=your-gmail-password
spring.mail.port=587
spring.mail.protocol=smtp
spring.mail.test-connection=false
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.smtp.ssl.trust=smtp.gmail.com
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.trust=smtp.gmail.com
Now, create a configuration class
ApiConfig.java
package com.techreloded.email.api.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;
@Configuration
public class ApiConfig {
@Primary
@Bean
public FreeMarkerConfigurationFactoryBean factoryBean() {
FreeMarkerConfigurationFactoryBean bean=new FreeMarkerConfigurationFactoryBean();
bean.setTemplateLoaderPath("classpath:/templates");
return bean;
}
}
Now, design your template file. under resources/template
email-template.ftl
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Diwali Greeting</title>
</head>
<body style="color:#ffffff;
background-image: url('https://res.cloudinary.com/people-matters/image/upload/fl_immutable_cache,w_624,h_351,q_auto,f_auto/v1508392723/1508392721.jpg');
height: 100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center"><br> <br>
<table width="600" border="0" cellspacing="0" cellpadding="0" style="float:left">
<tr>
<td align="left" valign="top"
style=" font-family: Arial, Helvetica, sans-serif; font-size: 13px; padding: 0px 15px 10px 15px;">
<div style="font-size: 48px; ">
<b>Greetings</b><br/><br/>
</div>
<div style="text-align:left">
Hi <b> ${name}</b>,<br/><br/>
Hope you are doing well. Here is a bright ful greetings for all viewers for dipawali 2020.
</div>
</td>
</tr>
</table> <br/> <br/></td>
</tr>
</table>
</body>
</html>
Also Read: Command line arguments in spring boot
Next, generate dto classes for request and response.
MailRequest.java
package com.techreloded.email.api.dto;
import lombok.Data;
@Data
public class MailRequest {
private String name;
private String to;
private String from;
private String subject;
}
package com.techreloded.email.api.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MailResponse {
private String message;
private boolean status;
}
Add Controller class
AppController.java
package com.techreloded.email.api.controller;
import com.techreloded.email.api.dto.MailRequest;
import com.techreloded.email.api.dto.MailResponse;
import com.techreloded.email.api.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class AppController {
@Autowired
private EmailService service;
@PostMapping("/sendingEmail")
public MailResponse sendEmail(@RequestBody MailRequest request) {
Map<String, Object> model = new HashMap<>();
model.put("name", request.getName());
return service.sendEmail(request, model);
}
}
Now, add EmailService.java
package com.techreloded.email.api.service;
import java.io.IOException;
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.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 com.techreloded.email.api.dto.MailRequest;
import com.techreloded.email.api.dto.MailResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@Service
public class EmailService {
@Autowired
private JavaMailSender sender;
@Autowired
private Configuration config;
public MailResponse sendEmail(MailRequest request, Map<String, Object> model) {
MailResponse response = new MailResponse();
MimeMessage message = sender.createMimeMessage();
try {
// set mediaType
MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
// add attachment
helper.addAttachment("logo.png", new ClassPathResource("logo.png"));
Template t = config.getTemplate("email-template.ftl");
String html = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
helper.setTo(request.getTo());
helper.setText(html, true);
helper.setSubject(request.getSubject());
helper.setFrom(request.getFrom());
sender.send(message);
response.setMessage("mail send to : " + request.getTo());
response.setStatus(Boolean.TRUE);
} catch (MessagingException | IOException | TemplateException e) {
response.setMessage("Mail Sending failure : "+e.getMessage());
response.setStatus(Boolean.FALSE);
}
return response;
}
}
And here is my Main Class
package com.techreloded.email.api;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.techreloded.email.api.dto.MailRequest;
import com.techreloded.email.api.dto.MailResponse;
import com.techreloded.email.api.service.EmailService;
@SpringBootApplication
public class SpringBootEmailFreemarkerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootEmailFreemarkerApplication.class, args);
}
}
Now, hit the controller with proper payload you should receive email in your Gmail inbox. Hope you found this blog helpful. Thanks.
The email will look like this:
We are a 360-degree software development company that provides cross-platform SaaS app development services to address varied software project requirements. We have an experienced team of Java, PHP, and Python developers who use advanced frameworks, tools, and SDKs to build scalable web and mobile applications with custom features. For more detail, reach us out at [email protected].
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Gaurav Kumar
He is always ready to grasp new tech and tools as per project requirement.