2019年,我刚接触测试架构和测试开发类的工作时,经常会有自动化发邮件的功能,大都是从各个平台自动化统计一些数据出来,每周定时发一封邮件给领导交差,回过头来再看看我发的邮件,不美观,不专业。这2年,也有想过不要再费劲去拼样式+变量字符串了,但由于我打工仔繁忙的属性,一直拖到现在。这周项目有空闲时间,我研究了一下,弄了个模板出来,业务代码一套,就成了!!!!!
技术选型
springboot+thymeleaf
基础配置
配置
#application.properties
spring.mail.host=192.168.19.232
spring.mail.username=bug@hookweb.com.cn #发件人邮箱
spring.mail.password=emailqa #发件人邮箱授权码,不是密码,如果有些企业邮箱本身不存在授权,直接用密码试试
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
spring.mail.port=25
spring.thymeleaf.prefix=classpath:/templates/
POM依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId><version>2.1.5.RELEASE</version></dependency>
HTML邮箱模板
最炫酷,最自由的方式,HTML模板任意定制,直接从网上下载最方便
<!DOCTYPE html>
<!--suppress ALL-->
<html xmlns:th="http://www.thymeleaf.org" xmlns:background-color="http://www.w3.org/1999/xhtml">
<head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="description" content="email code"><meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<!--邮箱验证码模板-->
<body>
<div style="background-color:#ECECEC; padding: 35px;"><table cellpadding="0" align="center"style="width: 800px;height: 100%; margin: 0px auto; text-align: left; position: relative; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; font-size: 14px; font-family:微软雅黑, 黑体; line-height: 1.5; box-shadow: rgb(153, 153, 153) 0px 0px 5px; border-collapse: collapse; background-position: initial initial; background-repeat: initial initial;background:#fff;"><tbody><tr><th valign="middle"style="height: 25px; line-height: 25px; padding: 15px 35px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: RGB(148,0,211); background-color: RGB(148,0,211); border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px;"><font face="微软雅黑" size="5" style="color: rgb(255, 255, 255); " th:text="${content}"> <!--/*@thymesVar id="msg" type="java"*/--></font></th></tr><tr><td style="word-break:break-all"><div style="padding:25px 35px 40px; background-color:#fff;opacity:0.8;"><h2 style="margin: 5px 0px; "><font color="#333333" style="line-height: 20px; "><font style="line-height: 22px; " size="4">尊敬的用户:</font></font></h2><!-- 中文 --><p >您好!感谢您使用****,您的账号正在进行邮箱验证,验证码为:<font color="#ff8c00"><!--/*@thymesVar id="recipienttype" type="java"*/--><div th:object="${bodyEntity}"><p th:text="*{recipienttype}"></p><p th:text="*{address}"></p></div><p th:text="${code}"></p></font>,有效期30分钟,请尽快填写验证码完成验证!</p><br><div style="width:100%;margin:0 auto;"><div style="padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;"><p>****团队</p><p>联系我们:********</p><br><p>此为系统邮件,请勿回复<br>Please do not reply to this system email</p><!--<p>©***</p>--></div></div></div></td></tr></tbody></table>
</div>
</body>
</html>
基础发邮件服务
package com.send.mail.services;
import java.util.Map;
public interface MailService {void sendHtmlMailOne(String to, String subject, String content);void sendHtmlMailMulti(String[] to, String subject, String content);
}
基础发邮件服务实现
package com.send.mail.services.impl;import com.send.mail.services.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
@Service
public class MailServiceImpl implements MailService {@Value("${spring.mail.username}") //直接从配置文件获取username的值private String from;@Autowiredprivate JavaMailSender javaMailSender;@Overridepublic void sendHtmlMailOne(String to, String subject, String content) {try {MimeMessage message = javaMailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setTo(to);//收件者helper.setFrom(from);//发送者helper.setSubject(subject);//主题helper.setText(content, true);//第二个参数true表示邮件正文是HTML格式的,该参数不传默认为false。javaMailSender.send(message);} catch (MessagingException e) {System.out.println("发送失败");}}@Overridepublic void sendHtmlMailMulti(String[] to, String subject, String content) {try {MimeMessage message = javaMailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setTo(to);//收件者helper.setFrom(from);//发送者helper.setSubject(subject);//主题helper.setText(content, true);//第二个参数true表示邮件正文是HTML格式的,该参数不传默认为false。javaMailSender.send(message);}catch (Exception e) {e.printStackTrace();}}
}
使用JavaMailSender发送邮件
注入JavaMailSender(由Spring容器管理)
使用MimeMessageHelper消息助手,可自定义设置发件人、收件人、抄送人等邮件信息
动态值
变量值
package com.send.mail.util;
import org.springframework.stereotype.Service;
@Service
public class GetCode {public String getCode() {String str = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // no zeroStringBuilder code = new StringBuilder();for (int i = 0; i < 6; i++) {int index = (int) (Math.random() * str.length());code.append(str.charAt(index));}return code.toString();}
}
对象传给HTML解析
package com.send.mail.util;
public class BodyEntity {private String recipienttype;private String address;public BodyEntity() {}public BodyEntity(String recipienttype, String address) {this.recipienttype = recipienttype;this.address = address;}public void setRecipienttype(String recipienttype) {this.recipienttype = recipienttype;}public void setAddress(String address) {this.address = address;}public String getRecipienttype() {return recipienttype;}public String getAddress() {return address;}
}
controller解析发送邮件
package com.send.mail.controller;
import com.send.mail.services.impl.MailServiceImpl;
import com.send.mail.util.BodyEntity;
import com.send.mail.util.GetCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.Map;
@RestController
public class IndexController {@Autowiredprivate MailServiceImpl mailService;@Autowiredprivate TemplateEngine templateEngine;@Autowiredprivate GetCode getCode;@GetMapping("/sendmail/{to}")public String sendmail(@PathVariable String to) throws MessagingException {//Thymeleaf提供了TemplateEngine来对模板进行渲染,通过Context构造模板中变量需要的值Context context = new Context();context.setVariable("title", "自定义的HTML内容标题");//设置templates模板里的title变量值context.setVariable("content","自定义的HTML内容标题");String mail = templateEngine.process("index.html", context);mailService.sendHtmlMailOne(to, "邮件标题", mail);return "sucess";}@GetMapping("/sendmailm/{to}")public String sendmailm(@PathVariable String[] to) throws MessagingException {//Thymeleaf提供了TemplateEngine来对模板进行渲染,通过Context构造模板中变量需要的值BodyEntity bodyEntity=new BodyEntity();bodyEntity.setRecipienttype("recipient's");bodyEntity.setAddress("danae@hookweb.com.cn");Context context = new Context();context.setVariable("title", "自定义的HTML内容标题");//设置templates模板里的title变量值context.setVariable("content","自定义的HTML内容标题");context.setVariable("code",getCode.getCode());context.setVariable("bodyEntity",bodyEntity);String mail = templateEngine.process("index.html", context);mailService.sendHtmlMailMulti(to, "邮件标题", mail);return "sucess";}
}