Sending Mail Template From Spring Boot Application Using Thymeleaf
Posted By : Himanshu Kumar | 29-Jan-2018
Thymeleaf is a cutting-edge server-side Java layout motor for both web and independent situations.
Thymeleaf's principle objective is to convey rich common formats to your advancement work process — HTML that can be effectively shown in programs and furthermore fill in as static models, taking into account more grounded joint effort being developed groups.
With modules for Spring Framework, a large group of combinations with your most loved devices, and the capacity to connect to your own particular usefulness, Thymeleaf is perfect for cutting-edge HTML5 JVM web advancement — in spite of the fact that there is substantially more it can do.
HTML layouts are written in Thymeleaf still look and work like HTML, letting the genuine formats that are keep running in your application continue filling in as helpful outline ancient rarities.
Shroud, IntelliJ IDEA, Spring, Play, even the best in class Model-View-Controller API for Java EE 8. Compose Thymeleaf in your most loved apparatuses, utilizing your most loved web-advancement system.
This particular lingo depends on the Thymeleaf Standard Dialect and is executed in a class called org.thymeleaf.spring4.dialect.SpringStandardDialect, which in certainty reaches out from org.thymeleaf.standard.standard dialect.
Other than every one of the highlights effectively
Utilize Spring Expression Language (Spring EL) as a variable articulation dialect, rather than OGNL. Subsequently, all ${...} and *{...} articulations will be assessed by Spring's Expression Language motor.
New characteristics for frame handling: the: field,
An articulation protest and strategy, #themes.code(...), which is proportional to the spring
An articulation protest and strategy, #mvc.uri(...), which is proportional to the spring:mvcUrl(...) JSP custom capacity (just in Spring 4.1+).
New DTDs for approval, including these new traits, and in addition new relating DOCTYPE interpretation rules.
Note that you shouldn't utilize this lingo specifically in an ordinary TemplateEngine question as a piece of its design. Rather, you should case another format motor class that plays out all the required arrangement steps: org.thymeleaf.spring4.SpringTemplateEngine.
Step 1:- Add maven dependency for
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
Step
package com.project.config;
import java.nio.charset.StandardCharsets;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.templatemode.StandardTemplateModeHandlers;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
@Configuration
public class ThymeleafConfig {
/**
* This method is use to get ClassLoaderTemplateResolver.
* @param Nothing.
* @return ClassLoaderTemplateResolver.
*/
@Bean
public ClassLoaderTemplateResolver htmlTemplateResolver(){
ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
emailTemplateResolver.setPrefix("/templates/");
emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setTemplateMode(StandardTemplateModeHandlers.HTML5.getTemplateModeName());
emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
return emailTemplateResolver;
}
}
Step 3:- Create a util class ThymeleafUtil to process the input data from
package com.project.util;
import java.util.Iterator;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
@Component
public class ThymeleafUtil {
@Autowired
private TemplateEngine tempTemplateEngine;
private static TemplateEngine templateEngine;
@PostConstruct
void init() {
templateEngine = tempTemplateEngine;
}
public static String getProcessedHtml(Map<String, Object> model,String templateName) {
Context context = new Context();
if (model != null) {
model.forEach((key,value) -> context.setVariable(key, value));
return templateEngine.process(templateName, context);
}
return "";
}
}
Step 4: Now from your util class where you have code for sending the email like MailServiceImplimentation class , you can send the dynamic data that you want to be on mail as the response of HTML template .And these dynamic data will be processed by TemplateEngine .
@Override
public void registrationMailSend(String to, String token) {
MimeMessage message = emailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
Map<String, Object> model = new HashMap<>();
model.put("url", serverUrl + "/#/login?token=" + token);
model.put("to", to);
helper.setTo(to);
String html = ThymeleafUtil.getProcessedHtml(model, EmailTemplate.REGISTRATION);
helper.setText(html, true);
helper.setSubject("Verification link for registration");
helper.setFrom(new InternetAddress(mailFrom, domainName).toString());
emailSender.send(message);
} catch (UnsupportedEncodingException | MessagingException e) {
logger.error("registrationMailSend exce: {}", e);
}
}
Step 5:- Create Email Template in the html file that you want to send email from your util class.
<!DOCTYPE html>
<html>
<head>
<title>Verification mail for registration</title>
<meta charset="UTF-8" />
</head>
<body style="font-family: sans-serif;">
<div
style="">
<div style="background-color: #fff; height: 594px; width: 500px; border: 5px solid lightgray;">
<div style="text-align: center; padding-top: 18px;">
<img alt=""
src="https://pbs.twimg.com/profile_images/874996574811770880/-p-n0XEA_400x400.jpg"
width="70" height="73" />
</div>
<div
style="width: 500px; position: relative; height: 145px; background-color: #000; margin-top: 21px; padding-top: 56px; text-align: center;">
<img alt=""
src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/Yes_Check_Circle.svg/1024px-Yes_Check_Circle.svg.png"
style="" width="60" height="60" />
<p style="color: #fff; font-size: 14px;">
<span>Verify Your Account</span>
</p>
</div>
<div style="font-size: 14px;">
<p style="margin-left: 13px;">Your account information</p>
<p style="margin-left: 13px;">
Account <span style="margin-left: 36px;" th:text="${to}">to</span>
</p>
</div>
<div
style="text-align: center; padding-top: 15px; padding-bottom: 9px;">
<a name="verify" th:href="@{${url}}" target="_blank"
style="padding:10px;background: #DB2828; outline: 0; border: 0; cursor: pointer; color: #fff; box-shadow: 0px 4px 5px 0px Gray !important; height: 45px; width: 199px; border-radius: 4px; font-size: 12px; text-transform: uppercase; text-decoration: none;">Verify
Your Account</a>
</div>
<div style="padding-left: 13px; font-size: 14px;margin-top: 18px">
<span>If you have any trouble to verify your account please
feel free to contact us</span> <span> thanks </span>
</div>
<div
style="background-color: gray; width: 500px; height: 59px; margin-top: 6px; text-align: -webkit-center; padding-top: 20px; font-size: 11px; color: #fff;">
<span>you have receiving this mail because you have an
account in bolenum-exchange . </span><span> you are not sure why
you'r receiving this,please contact us</span>
</div>
</div>
</div>
</body>
</html>
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
Himanshu Kumar
Himanshu Kumar is a seasoned Backend Developer with extensive experience in the industry. He has a deep understanding and hands-on expertise in a range of technologies, including Core Java, Spring-Boot, Hibernate, Apache Kafka messaging queue, and blockchain development with Ethereum, Tron, and smart contract development. He is also well-versed in relational databases like MySQL and PostgreSQL. His proficiency in API implementation, web services, development testing, and deployment has contributed to the successful delivery of various client projects, such as Wethio Exchange, Hedgex Exchange, Envoychain payment gateway based on Stellar assets, and more. With a creative mind and excellent analytical skills, Himanshu enjoys staying up to date with the latest technologies and exploring new ideas to bring value to his work.