我们平时发送邮件基本都是以纯文本的形式,达到通知的目的就可以了,如果要给我们的客户发纯文本邮件未免显得太low,用户体验性很不好,那怎么解决这个问题呢?
so easy 我们的html模板邮件来了 。
只要html css功底到位,那发出去的邮件都可以有一个质的提升:
横看成岭侧成峰 ,远近高低各不同
废话少说,小试牛刀:
1、首先要准备好一个html模板,
这里简单写了个学校录取名单的模板
student.html 代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title></title>
<style>
tr {font-size: 15px;}
td {text-align: center; line-height: 50px;color:#74787E;font-size: 15px;}
th {border-bottom: 0.5px solid #ddd; height: 40px;line-height: 40px;}
.bottom_line {border-bottom: 1px solid #74787E; height: 40px;line-height: 40px;}
body{ margin: 0; padding: 0; border: 0; }
.buttom_tip {font-size: 13px;color:#74787E;}
</style>
</head>
<body >
<div align="center" style="background-color: #FFF;width: 100%;">
<a href="https://rep.hce-haier.com">
<img src="https://img1.baidu.com/it/u=1945399994,1849022294&fm=26&fmt=auto&gp=0.jpg"
style="width: 200px;height: 200px;margin: 30px 30px;" />
</a>
</div>
<div align="center" >
<div style="width: 48%" align="left">
<h5><span th:text="${year}"></span> 年录取名单</h5>
<table cellspacing="0" cellpadding="0" style="width: 100%;">
<tr >
<th style="text-align: left">姓名</th>
<th>年龄</th>
<th>性别</th>
<th>准考证号</th>
<th>成绩</th>
<th>排名</th>
</tr>
<tr th:each="std:${datalist}">
<td style="text-align: left" th:text="${std.name}"> </td>
<td th:text="${std.age}"> </td>
<td th:if="${std.sex eq '1'}">
<font color="blue">男</font>
</td>
<td th:if="${std.sex eq '2'}">
<font color="red">女</font>
</td>
<td th:text="${std.card}"> </td>
<td th:text="${std.score}"> </td>
<td th:text="${std.order}"> </td>
</tr>
</table>
<p style="font-size: 17px;" class="bottom_line">此致</p>
<h5>莘县一中</h5>
<h5>欢迎第47届新同学入学</h5>
</div>
</div>
<div align="center" >
<div style="width: 98%;" >
<p class="buttom_tip" style="text-align:left;"> </p>
<p class="buttom_tip" style="text-align:left;"> </p>
</div>
</div>
</body>
</html>
2、默认maven项目:
pom.xml 添加依赖
<!--邮件模板依赖 -->
<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>
</dependency>
3、application.properties 配置文件如下
# SMTP 地址
spring.mail.host=smtp.163.com
# 发件人邮箱地址
spring.mail.username=XXXXXX@163.com
# 邮箱密码(授权码)
spring.mail.password=XXXXXXXX
# 编码
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=false
spring.mail.properties.mail.smtp.starttls.required=false
# 模板路径 resources文件夹下的路径
spring.thymeleaf.prefix=classpath:/templates/
# 模板类型
spring.thymeleaf.servlet.content-type: text/html
# 是否缓存
spring.thymeleaf.cache: false
# HTML 模板
spring.thymeleaf.mode: HTML5
spring.thymeleaf.check-template-location=true
4、java 代码如下:
package com.weryou.email.kit;
import java.util.Map;
/**
* @ClassName MailKit
* @Description
* @Author weryou
* @Date 2021/7/19 22:38
* @Version 1.0
**/
public class MailKit {
//标题
private String title;
//内容
private String content;
//接收人邮件地址
private String email;
//附加,value 文件的绝对地址/动态模板数据
private Map<String, Object> attachment;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Map<String, Object> getAttachment() {
return attachment;
}
public void setAttachment(Map<String, Object> attachment) {
this.attachment = attachment;
}
}
package com.weryou.email.model;
/**
* @ClassName StudentVo
* @Description
* @Author weryou
* @Date 2021/7/17 22:27
* @Version 1.0
**/
public class StudentVo {
private String name;
private String sex;
private int age;
private String card;
private int score;
private int order;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getCard() {
return card;
}
public void setCard(String card) {
this.card = card;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
}
package com.weryou.email.service;
import com.weryou.email.kit.MailKit;
import com.weryou.email.model.StudentVo;
import java.util.List;
public interface SendEmailService {
/**
* 发送邮件
* @param mailKit
* @param modelName
* @param emailType
* @return
*/
boolean sendTemplateMail(MailKit mailKit, String modelName, String emailType);
/**
* 获取学生信息
* @return
*/
List<StudentVo> getStudentInfo();
}
package com.weryou.email.service.impl;
import com.weryou.email.kit.MailKit;
import com.weryou.email.model.StudentVo;
import com.weryou.email.service.SendEmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName SendEmailServiceImpl
* @Description
* @Author weryou
* @Date 2021/7/19 21:48
* @Version 1.0
**/
@Service
public class SendEmailServiceImpl implements SendEmailService {
private final static Logger log = LoggerFactory.getLogger(SendEmailServiceImpl.class);
private final static String SEX_1 = "1";//男生
private final static String SEX_2 = "2";//女生
@Autowired
private TemplateEngine templateEngine;
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String from;
/**
* thymeleaf模板
* @param emailType
*/
@Async
@Override
public boolean sendTemplateMail(MailKit mailKit, String modelName, String emailType) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
// 昵称
String nickname = "ShenXian NO.1 School";
// From: 发件人
mimeMessage.setFrom(new InternetAddress(from, nickname, "UTF-8"));
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
//messageHelper.setFrom(from);// 发送人的邮箱
if(mailKit.getEmail().contains(",")){
String[] emails = mailKit.getEmail().split(",");
int s = 1;
for (String email:emails){
if(s==1){
//第一个收件人用setTo
messageHelper.setTo(email);
}else{
//多个收件人用addTo
messageHelper.addTo(email);
}
s++;
}
}else{
messageHelper.setTo(mailKit.getEmail());
}
//标题
messageHelper.setSubject(mailKit.getTitle());
//使用模板thymeleaf
Context context = new Context();
//定义模板数据
context.setVariables(mailKit.getAttachment());
//获取thymeleaf的html模板
String emailContent = templateEngine.process(modelName,context);
messageHelper.setText(emailContent,true);
//发送邮件
javaMailSender.send(mimeMessage);
} catch (MessagingException | UnsupportedEncodingException e) {
log.error("模板邮件发送失败->message:{}",e.getMessage());
return false;
}
return true;
}
@Override
public List<StudentVo> getStudentInfo() {
List<StudentVo> lists = new ArrayList<StudentVo>();
StudentVo vo1 = new StudentVo();
vo1.setAge(14);
vo1.setCard("20210001");
vo1.setName("赵小明");
vo1.setScore(686);
vo1.setOrder(1);
vo1.setSex(SendEmailServiceImpl.SEX_1);
lists.add(vo1);
StudentVo vo2 = new StudentVo();
vo2.setAge(15);
vo2.setCard("20210002");
vo2.setName("王小花");
vo2.setScore(677);
vo2.setOrder(2);
vo2.setSex(SendEmailServiceImpl.SEX_2);
lists.add(vo2);
StudentVo vo3 = new StudentVo();
vo3.setAge(14);
vo3.setCard("20210003");
vo3.setName("张丽丽");
vo3.setScore(675);
vo3.setOrder(3);
vo3.setSex(SendEmailServiceImpl.SEX_2);
lists.add(vo3);
return lists;
}
}
package com.weryou.email.controller;
import com.weryou.email.kit.MailKit;
import com.weryou.email.model.StudentVo;
import com.weryou.email.service.SendEmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @ClassName SendEmailCtrl
* @Description
* @Author weryou
* @Date 2021/7/19 20:09
* @Version 1.0
**/
@RestController
@RequestMapping("/email")
@Validated
public class SendEmailCtrl {
private final static Logger log = LoggerFactory.getLogger(SendEmailCtrl.class);
@Autowired
private SendEmailService sendEmailService;
/**
* 发送邮件
* @return
*/
@GetMapping("/templateMail")
@ResponseBody
public String templateMail() {
List<StudentVo> voList = sendEmailService.getStudentInfo();
MailKit mailKit = new MailKit();
mailKit.setTitle("录取名单");
mailKit.setContent("莘县一中录取学生名单");
String emailAddr = "12345678@qq.com";
mailKit.setEmail(emailAddr);
try {
Map<String,Object> map = new HashMap<>();
map.put("username","All");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
log.info("录取名单邮件发送时间:"+df.format(new Date()));
map.put("year",df.format(new Date()).toString().substring(0,4));
map.put("datalist",voList);
mailKit.setAttachment(map);
boolean flag = sendEmailService.sendTemplateMail(mailKit,"student","SCHOOL");
if(flag){
log.info("邮件发送成功!");
}else{
log.warn("邮件发送失败!");
}
} catch (Exception e) {
log.error("邮件发送异常:",e);
return "发送失败";
}
return "发送成功";
}
}
5、代码目录结构:
6、把邮件地址替换成真实的地址,启动服务见证奇迹吧
7、http://localhost:8080/email/templateMail
效果图:
End 2021年7月19日23:02:56