使用 FreeMarker模板 Springboot 发送邮件
2024-10-01 06:43:56
四、使用 FreeMarker模板
HTML 标签的字符串拼接是一件很棘手的事。因为在你的大脑中解析HTML标签并想象它在渲染时会是什么样子是挺困难的。而将HTML混合在Java代码中又会使得这个问题更加复杂。
因此 Spring 给出的解决方案是:使用模板生成 HTML 文本,有多种模板方案可供选择,包括Apache Velocity和freemarker。这里仅介绍 freemarker模板的用法(假设读者已经熟悉了 freemarker模板并知道如何在 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: %;
border-collapse: collapse;
} td, th {
font-size: 1em;
border: 1px solid #5B4A42;
padding: 3px 7px 2px 7px;
} th {
font-size: .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
spring.mail.username=123456@qq.cn
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("zhoucui_test@163.com"));//发送给谁
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测试成功。
最新文章
- python查找指定目录下所有文件,以及改文件名的方法
- jenkins2 groovy语法
- MVC5 + EF6 + Bootstrap3 (9) HtmlHelper用法大全(下)
- Laravel 5 基础(八)- 模型、控制器、视图基础流程
- redis(二)redis+TCMALLOC高性能的缓存服务器的安装配置
- StreamWrite-StreamRead 读写文本文件
- Bitmap
- Linux分区规划与xshell使用排错
- Linux源码包安装程序
- Spring 的 AOP 进行事务管理的一些问题
- ScreenToGif 使用教程
- IDEA创建Spring+SpringMVC+MyBatis(SSM)极简入门(上)
- Delphi XE5 Android 调用 Google ZXing
- android listview优化:滑动时颜色错乱问题
- servlet、servlet容器和web应用程序的关系
- java通过url在线预览Word、excel、ppt、pdf、txt文档
- ajax无刷新方式对form表单进行赋值!
- 强大!HTML5 3D美女图片旋转实现教程
- HDU4436_str2int
- jQuery实现复选框 全选、反选、全不选
热门文章
- Android前后台切换的监听
- 题解 P6098 【[USACO19FEB]Cow Land G】
- Java程序员想年后跳槽,对JVM没有深入的理解,我劝你还是别跳了
- Dynamics CRM - 如何创建一个新的 Organization
- Django框架(七):模型(三) 关联、模型类的属性
- 关于gc中对象回收算法的认识
- Java并发编程:CountDownLatch、CyclicBarrier和 Semaphore , Condition
- PAT Advanced 1092 To Buy or Not to Buy (20) [Hash散列]
- Java基础二(2020.1.14)
- C盘满了解决办法之hiberfil.sys文件