“This is the fourth day of my participation in the First Challenge 2022. For details: First Challenge 2022”
๐จ๐ Author: Bug Bacteria
โ๏ธ blog: CSDN, Nuggets, etc
๐ public account: Magic House of the Circle of the Apes
๐ซ special statement: original is not easy, reprint please attach the original source link and this article statement, thank you for your cooperation.
๐ Copyright notice: part of the text or pictures in the article may come from the Internet or Baidu Encyclopedia, if there is infringement, please contact bug bacteria processing.
Hi, family. I’m the bug. Here I go again. Today we are going to talk about something, OK, and we will continue the Series of articles on SpringBoot. Hope to help more beginners quickly start!
In the process of reviewing articles, if you think the articles are helpful to you at all, please don’t be too mean with your likes and bravely light up the articles ๐. Your likes (collect โญ๏ธ+ pay attention to ๐จ port + message board) are the best encouragement and support for bugs on my creation path. Time does not abandon ๐๐ปโ๏ธ, creation stopped ๐, refueling ๐ป
A: the preface
Continuation of the previous article, we have successfully realized the email to send reminders, right, friends follow me all the way to read, do you feel more relaxed, after all, I will not be very long. If you go on like this, you’ll learn one point of knowledge every day, which will make thirty points in a month, and when that adds up, you’ll be the next big guy. If there is a small partner directly inserted midway, but also please trouble to see the content of a few periods, otherwise rrtly follow, must suffer a great loss, go to my column “SpringBoot zero foundation entry” from the beginning to follow up.
Today, I will bring you some knowledge points related to Thymeleaf template engine. Usually, some emails have format requirements, that is, the format is fixed. I don’t know if you have encountered such requirements in your life scenes, how should we implement them? All right, without further ado, take that!
2. Business scenarios
1. How to use Thymeleaf as template mail?
What is Thymeleaf?
Thymeleaf is a next-generation Java templating engine that is similar to traditional Java templating engines such as Velocity and FreeMarker, but unlike traditional Java templating engines, Thymeleaf supports HTML prototyping.
SpringBoot also provides an automated configuration solution for Thymeleaf, so it is very convenient to use Thymeleaf in SpringBoot, which is what we will cover today.
Some of your friends might ask, why not FreeMarker? It’s ok if you don’t. Yes, FreeMarker can do templates, but with Thymeleaf, previewing is very convenient, you can open it directly in the browser, it’s just a static web page with an.HTML suffix.
So today we’re going to skip the usual routine and teach you how to use Thymeleaf as an email template, okay? Let’s read on!
2. Introduce the Thymeleaf dependency
<! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>Copy the code
3. Customize static templates
I’ll just define a random mail.html as a right-click template. If you’re too lazy to do it yourself, you can try mine first.
<! DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"><head> <meta charset="UTF-8"> <title>Thymeleaf mail template </title> </head> <body> <p> This is a list of students: Please find the < / p > < table border = "1" > < tr > < td > school < / td > < td th: text = "${school}" > < / td > < / tr > < tr > < td > class < / td > < td Th: text = "${className}" > < / td > < / tr > < tr > < td > name < / td > < td th: text = "${name}" > < / td > < / tr > < / table > < div style = "color: red;" > < p style = "max-width: 100%; clear: both; </div> </body> </html>Copy the code
4, send mail template implementation
A, first we define a [static template mail configuration] model parameter body, pay attention to code needs specification. Inherit mail this VO, the need for small partners can go to the previous take, here is not much repetition ha.
package com.example.demo.component.mail.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.List; /** * @author luoYong * @version 1.0 * @date 2022/1/18 11:17 */ @apimodel (value = "static template email configuration ",description = Public class ThymeleafMail extends Mail {@apiModelProperty (" static File parameters ") private List<Variable> variables; @apiModelProperty (" static file name + suffix ") private String Template; public List<Variable> getVariables() { return variables; } public void setVariables(List<Variable> variables) { this.variables = variables; } public String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; }}Copy the code
SetVariable () and templateEngine.process() must be specified when you send the static template configuration, which is the fixed parameter assignment for your static template. So need, so I directly according to the required parameters of the package configuration, if you have a better idea or idea, then according to your own, I wrote just to give a general reference.
B, then define a class method, the core is to implement the mail static template send. The specific implementation of the code is as follows:
/** * Configure static templates */ public void sendThymeleafMail(ThymeleafMail Model) throws MessagingException {MimeMessage MimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper msg = new MimeMessageHelper(mimeMessage, true); Msg.setfrom (model.getsendMailAccount ()); / / mail recipients MSG. SetTo (model. GetAcceptMailAccount ()); Msg.setsubject (model.getTheme()); Msg.setsentdate (model.getsendTime ()); Context context = new Context(); Model.getvariables ().foreach (p -> {context.setvariable (p.getName(), p.getValue())); }); // Assign static page arguments to String process = templateEngine.process(model.getTemplate(), context); // Specify static page template msg.settext (process, true); javaMailSender.send(mimeMessage); }Copy the code
MimeMessage and MimeMessageHelper are used as two mail construction classes and mail sending and receiving information classes. For details, users can refer to the documents on the official website. Here I will not explain in depth, please kindly understand.
Cese = MailTest; cese = MailTest; cese = MailTest; Here are the test cases, and you can also define the contents of your email:
/** * Configure static templates */ @testPublic void testSendThymeleafMail() throws MessagingException {// Initialize ThymeleafMail mailModel = new ThymeleafMail(); Mailmodel.settheme (" This is a test email "); / / set the mail subject mailModel. SetSendMailAccount (" [email protected] "); / / set the email sender mailModel. SetAcceptMailAccount (" [email protected] "); Mailmodel.setsendtime (new Date()); List<Variable> variables = new ArrayList<>(); Variable variable1 = new Variable(); variable1.setName("school"); Variable1. setValue(" tsinghua Affiliated primary School "); Variable variable2 = new Variable(); variable2.setName("className"); Variable2.setvalue (" six (1) classes "); Variable variable3 = new Variable(); variable3.setName("name"); Variable3. SetValue (" ronaldinho "); variables.add(variable1); variables.add(variable2); variables.add(variable3); mailModel.setVariables(variables); mailModel.setTemplate("mail.html"); / / specified static page you just created sendMailBuild. SendThymeleafMail (mailModel); }Copy the code
D, the static template email is sent successfully, and the body of the email is in the template format defined by me. Screenshot below:
The above has been tested! Although template style is a bit ugly, but this is not the main focus, mainly is the email template succeeded, after all, a professional front-end engineer checks this part of the template style for us, so we don’t need to worry we back-end development, my this article teaching task is completed ~ take the liberty to ask, your test pass? If there is failure to send or send error, please post your question in the comment section, let’s communicate together, I think the power of one person is limited, but the power of a group of people is infinite, mutual help has always been a traditional Chinese virtue.
. .
OK, that’s all for this episode. If you have any questions, feel free to comment in the comments section. See you next time.
Three, the past popular recommendation
Springboot series (12) : how to code to send email reminder environment configuration (preparation)
Springboot series (12) : How to code simple email (part 1)
Springboot series (12) : how to code the implementation of pictures, doc and other attachments to mail (in the middle)
Springboot series (12) : how to code to achieve a large email send disk (summary)
. .
If you want to learn more, you can pay attention to the bug bug column “SpringBoot Zero-based Introduction”, from scratch, from zero to one! Hope I can help you.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
โ๏ธ Be who you want to be, there is no time limit, you can start whenever you want,
๐ You can change from now on, you can also stay the same, this thing, there are no rules to speak of, you can live the most wonderful yourself.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
โ
๐ If this article is helpful to you, please leave a like! (# ^. ^ #);
๐ if you like the article shared by bug fungus, please give bug fungus a point of concern! (เน ‘แด โต เน);
๐ if you have any questions about the article, please also leave a message at the end of the article or add a group [QQ communication group :708072830];
๐ In view of the limited personal experience, all views and technical research points, if you have any objection, please directly reply to participate in the discussion (do not post offensive comments, thank you);
๐ copyright notice: original is not easy, reprint please attach the original source link and this article statement, all rights reserved, piracy will investigate!! thank you