springboot+Thymeleaf实现发送Email模板邮件
在后台服务器中发送邮件已经是一个非常常用的功能了。通常来说虽然HTML并非是一个非常标准的信息格式,但是至少许多邮件客户端都至少支持一部分标记语言。 在这边教程中主要是关于教你如何在Spring Boot 应用中发送邮件以及使用非常简单强大的Thymeleaf模板引擎来制作邮件内容。
发送邮件效果展示:
本文支持邮件类型:
- 纯文本邮件
- 图片邮件
- 带附件的邮件
导入pom依赖
<!-- 发送邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
邮件服务器属性配置(Properties configuration)
通常情况下,如果所需要的依赖在 class path 中都是可用的话,这时候Spring会自动帮你注册一个默认实现的邮件发送服务 (default mail sender service)。 spring.mail.host 属性已经被自动定义了, 所有我们所需要做的事情就是把这个属性添加到我们应用的 application.properties 配置文件中。
为了防止springboot项目打包成jar文件之后,读取不到文件,我们把图片和附件都放在服务器指定路径上,直接读取该文件。
#mail
spring.mail.host=smtp.163.com
spring.mail.username=*********@163.com
spring.mail.password=********
spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.starttls.enable=false
spring.mail.properties.mail.smtp.starttls.required=false
#html template path (resources/templates/email/template.html)
templatePath=email/template
#mail image path
imagePath=D:\\image\\logo.jpg
#imagePath=/neworiental/web/cpbm/image/logo.jpg
邮件发送的工具类
/**
* 发送邮件工具类
* @author
*
*/
@Component
public class SendEmailUtils {
private final static Logger logger = LoggerFactory.getLogger(SendEmailUtils.class);
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private TemplateEngine templateEngine;
/**
* html模板邮件
* @param from 发件人
* @param to 收件人
* @param subject 邮件主题
* @param emailParam 给模板的参数
* @param template html模板路径(相对路径) Thymeleaf的默认配置期望所有HTML文件都放在 **resources/templates ** 目录下,以.html扩展名结尾。
* @param imagePath 图片/文件路径(绝对路径)
* @throws MessagingException
*/
public void thymeleafEmail(String from,String[] to, String subject,EmailParam emailParam,String template,String imagePath) throws MessagingException {
MimeMessage mimeMessage =javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo(to);
mimeMessageHelper.setSubject(subject);
// 利用 Thymeleaf 模板构建 html 文本
Context ctx = new Context();
// 给模板的参数的上下文
ctx.setVariable("emailParam", emailParam);
// 执行模板引擎,执行模板引擎需要传入模板名、上下文对象
// Thymeleaf的默认配置期望所有HTML文件都放在 **resources/templates ** 目录下,以.html扩展名结尾。
// String emailText = templateEngine.process("email/template", ctx);
// emailText的最终路径为:**resources/templates/XXX.html,templatePath的值替换XXX
String emailText = templateEngine.process(template, ctx);
mimeMessageHelper.setText(emailText, true);
// 添加附件,第一个参数表示添加到 Email 中附件的名称,第二个参数是图片资源
// FileSystemResource logoImage= new FileSystemResource("D:\\image\\logo.jpg");
FileSystemResource logoImage = new FileSystemResource(imagePath);
//一般图片调用这个方法
mimeMessageHelper.addInline("logoImage", logoImage);
//一般文件附件调用这个方法
//mimeMessageHelper.addAttachment("logoImage", logoImage);
javaMailSender.send(mimeMessage);
}
}
邮件参数实体类EmailParam.java
/**
* 邮件参数实体类
* @author
*
*/
public class EmailParam {
private String itemName;//产品名称
private String stuName;//学生姓名
private String updateContent;//变更操作
private String updatePerson;//操作人员
private String updateDate;//操作时间
private String remarks;//备注
//省略get、set方法
}
Html模板文件email.html
Thymeleaf的默认配置期望所有HTML文件都放在 **resources/templates ** 目录下,以.html扩展名结尾。
在项目中的路径:**resources/templates/email/email.html
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Siemens Sinnovation</title>
<style>
.button {
background-color: #4CAF50;
border-radius: 12px;
border: none;
color: white;
padding: 10px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 18px;
margin: 4px 2px;
cursor: pointer;
box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
.button:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
</style>
</head>
<body style="margin: 0;padding: 0;">
<table align="center" border="1" cellpadding="0" cellspacing="0" width="600px">
<tr>
<td>
<table align="center" border="0" cellpadding="0" cellspacing="0" width="600"
style="border-collapse: collapse;">
<tr>
<td align="center" style="padding: 40px 0 30px 0;">
<!---->
<img src='cid:logoImage' alt='前途出国' title='前途出国' style='width:183px height:47.50px'>
</td>
</tr>
<tr>
<td bgcolor="#ffffff" style="padding: 0px 30px 20px 30px">
<h4>产品报名系统变更通知:</h4>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td colspan="2" style="padding: 0 0 3px 0">变更操作:<span th:text="${emailParam.updateContent}">啊啊啊地方规划局快乐靠方法如何加快了开发地方</span></td>
</tr>
<tr>
<td style="padding: 12px 0 3px 0">产品名称:<span th:text="${emailParam.itemName}">的实际哦按非hi哦发货iOS恶</span></td>
</tr>
<tr>
<td style="padding: 12px 0 3px">学生姓名:<span th:text="${emailParam.stuName}">啊啊啊</span></td>
</tr>
<tr>
<td style="padding: 12px 0 3px">操作人员:<span th:text="${emailParam.updatePerson}">啊啊啊</span></td>
</tr>
<tr>
<td style="padding: 12px 0 3px">操作时间:<span th:text="${emailParam.updateDate}">啊啊啊</span></td>
</tr>
<tr>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td style="padding: 20px 0px 10px 0px">
Team Member:
</td>
</tr>
<tr th:each="member :${members}">
<td style="padding: 5px 0px 5px 0px"><span
th:text="${member()}+', Email: '+${member()}"></span>
</td>
</tr>
</table>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<table cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="center" style="padding: 5px 0px 5px 0px">
<a class="button" href="http://www.baidu.com" >查看详情</a>
</td>
</tr>
</table>
</tr>
</table>
</body>
</html>
Controller调用邮件工具类发送邮件
@RestController
@RequestMapping("/test")
public class ItemController {
private final Logger log = LoggerFactory.getLogger(ItemController.class);
@Value("${spring.mail.username}")
private String from;
@Value("${templatePath}")
private String templatePath;
@Value("${imagePath}")
private String imagePath;
@Autowired
private SendEmailUtils sendEmailUtils;
/**
* email
* @param itemIds
* @param response
*/
@PostMapping(value ="/email", produces = "text/plain;charset=UTF-8")
public void testEmaili(String itemIds,HttpServletResponse response/*,
HttpServletRequest request, HttpSession session,
@RequestHeader("Authorization") String authToken, Principal puser*/) {
try {
EmailParam emailParam = new EmailParam();
emailParam.setStuName("张阿牛");
emailParam.setItemName("亚太银行账目统计");
emailParam.setUpdateContent("付款到账");
emailParam.setUpdatePerson("盖茨");
emailParam.setRemarks("成功到账");
//此处to数组输入多个值,即可实现批量发送
String [] to={"**********@163.cn"};
sendEmailUtils.thymeleafEmail(from, to, "这是一封测试邮件主题", emailParam, templatePath, imagePath);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}