使用 FreeMarker模板 Springboot 发送邮件
Posted 小周lucky
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用 FreeMarker模板 Springboot 发送邮件相关的知识,希望对你有一定的参考价值。
四、使用 FreeMarker模板
html 标签的字符串拼接是一件很棘手的事。因为在你的大脑中解析HTML标签并想象它在渲染时会是什么样子是挺困难的。而将HTML混合在Java代码中又会使得这个问题更加复杂。
因此 Spring 给出的解决方案是:使用模板生成 HTML 文本,有多种模板方案可供选择,包括Apache Velocity和Thymeleaf。这里仅介绍 Thymeleaf 模板的用法(假设读者已经熟悉了 Thymeleaf 模板并知道如何在 SpringBoot 中使用它们)。
1、在项目templates目录新建Freemarker模板 — message.ftl
<html> <head> <meta charset="UTF-8"> <title>消息通知</title> </head> <style type="text/css"> table { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; width: 100%; border-collapse: collapse; } td, th { font-size: 1em; border: 1px solid #5B4A42; padding: 3px 7px 2px 7px; } th { font-size: 1.1em; text-align: center; padding-top: 5px; padding-bottom: 4px; background-color: #24A9E1; color: #ffffff; } </style> <body> <div> <h2>邮件消息通知</h2> <table id="customers"> <tr> <th>MessageCode</th> <th>MessageStatus</th> <th>Cause</th> </tr> <tr> <td>${(params.messageCode)!""}</td> <td>${(params.messageStatus)!""}</td> <td>${(params.cause)!""}</td> </tr> </table> </div> </body> </html>
2、定义发送邮件渲染对象
发送内容为object,通过模板渲染方式接收内容,如下所示
import lombok.Data; @Data public class Message { private String messageCode; private String messageStatus; private String cause; }
3、在application.properties文件中配置mail信息
spring.mail.host=smtp.exmail.qq.com [email protected] spring.mail.password=123456 spring.mail.default-encoding=UTF-8
4、编写EmailService服务接口
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
@Service
@Configuration
public class EmailService {
//邮件的发送者
@Value("${spring.mail.from}")
private String from;
//注入MailSender
@Autowired
private JavaMailSender javaMailSender;
//发送邮件的模板引擎
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
public void sendMessageMail(Object params, String title, String templateName){
try{
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo(InternetAddress.parse("[email protected]"));//发送给谁
mimeMessageHelper.setSubject("【" + title + "-" + LocalDate.now() + " " + LocalTime.now().withNano(0) + "】");//邮件标题
Map<String,Object> model = new HashMap<>();
model.put("params",params);
try{
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
try{
String text = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);
mimeMessageHelper.setText(text,true);
javaMailSender.send(mimeMessage);
}catch (TemplateException e){
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}
}catch (MessagingException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
}
5、新建controller测试
import com.longteng.diamond.domain.Message; import com.longteng.diamond.service.EmailService; import freemarker.template.Configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import javax.annotation.Resource; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @Controller public class MimeEmailController { @Resource private EmailService emailService; @RequestMapping(value = "/sendMessage", method = RequestMethod.GET) @ResponseBody public String sendMailMessage() { Message message = new Message(); message.setMessageCode("MissingParameter"); message.setMessageStatus("Failed"); message.setCause("缺少参数,请确认"); emailService.sendMessageMail(message, "测试消息通知", "message.ftl"); return "sendMessage"; } }
访问http://localhost:8081/send 出现1测试成功。
以上是关于使用 FreeMarker模板 Springboot 发送邮件的主要内容,如果未能解决你的问题,请参考以下文章