下面介绍两种发送模板邮件的方法,第一种适合springboot和对thymleaf模板语法比较精通的开发者,第二种则比较通用,因为仅使用了apache-commons-mail和vecolity模板引擎,语法简单容易上手,通用性强,所以个人比较喜欢用第二种。
一、 使用springboot-starter-mail和thymeleaf发送模板邮件
1. 首先引入依赖
<!-- 添加spring-boot-starter-mail包引用 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--thymeleaf 模板技术 用于发送邮件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2. 相关的配置
spring.mail.host=smtp.163.com
spring.mail.username=***
spring.mail.password=**** //需要去邮件服务器后台获取授权码,此为授权码
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.thymeleaf.cache=false
## 表示邮件模板存放于该目录下
spring.thymeleaf.prefix=classpath:/mailtemplate/
spring.thymeleaf.suffix=.html
spring.thymeleaf.content-type=text/html
3. 根据模板生成相应html
//模板引擎对象
@Autowired
private TemplateEngine templateEngine;
//获取生成的模板
Map<String, String> dataMap = new HashMap<>();
dataMap.put("title", "用户名激活");
dataMap.put("url", "233");
Context context = new Context();
context.setVariables(dataMap);
String emailText = templateEngine.process("emailTemplates", context);
4. 发送邮件
@Autowired
private JavaMailSender javaMailSender;
@Override
public void sendHtml(String to, String subject) {
try {
//获取生成的模板
Map<String, String> dataMap = new HashMap<>();
dataMap.put("title", "用户名激活");
dataMap.put("url", "233");
Context context = new Context();
context.setVariables(dataMap);
String emailText = templateEngine.process(templatesName, context);
//消息处理助手对象
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
//设置发件人
helper.setFrom(sender);
//设置收件人
helper.setTo(to);
//设置邮件标题
helper.setSubject("主题:用户名激活");
//设置邮件内容 ,true 表示发送html 格式
helper.setText(emailText, true);
javaMailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
5. 附件:html模板(需掌握thymleaf模板语法: https://www.cnblogs.com/jiangbei/p/8462294.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>userInfo</title>
</head>
<body>
title: <span th:text="${title}"></span>
</body>
</html>
二、使用apache-commons-mail包和 vecolity 模板引擎来发送模板邮件
- 依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
<!--模板引擎-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
- 根据模板生成 html文件或者 html 的字符串
## 模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试velocity模板</title>
</head>
<body>
#if(${var1})
<p>获取变量: ${var1}</p>
#end
<br/>
<p>测试循环:</p>
<ul>
#foreach($pkg in ${var2})
<li style="color:red">$pkg</li>
#end
</ul>
</body>
</html>
## 渲染模板
public class RenderUtils {
public static final String encode = Charset.forName("UTF-8").name();
public static void main(String[] args) {
System.out.println(getVmRenderString("/vmtpl.vm",
new HashMap<String, Object>() {{
put("var1", "测试");
put("var2", Arrays.asList("4", "5", "6"));
}}
));
}
/**
* 根据velocity引擎生成文件
*
* @param templatePath resource文件夹下的模板地址,如:/vmtempalte/vmtpl.vm
* @param outputFile 输出文件地址
* @param objectMap 变量值:
* <p>
* 模板插值判断语法:
* #if(${restControllerStyle})
* #else
* #end
* <p>
* 模板插值循环语法:
* #foreach($pkg in ${table.importPackages})
* import ${pkg};
* #end
*/
public static void getFileByVmEngine(String templatePath, String outputFile, Map<String, Object> objectMap) {
try {
VelocityEngine velocityEngine = initVelocityEngine();
Template template = velocityEngine.getTemplate(templatePath, encode);
FileOutputStream fos = new FileOutputStream(outputFile);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, encode));
template.merge(new VelocityContext(objectMap), writer);
writer.close();
} catch (IOException e) {
System.out.println("根据模版引擎生成目标失败");
e.printStackTrace();
}
}
/**
* 根据velocity引擎生成文件
*
* @param templatePath resource文件夹下的模板地址,如:/vmtempalte/vmtpl.vm
* @param objectMap 变量值:
* <p>
* 模板插值判断语法:
* #if(${restControllerStyle})
* #else
* #end
* <p>
* 模板插值循环语法:
* #foreach($pkg in ${table.importPackages})
* import ${pkg};
* #end
*/
public static String getVmRenderString(String templatePath, Map<String, Object> objectMap) {
String render = "";
try {
VelocityEngine velocityEngine = initVelocityEngine();
Template template = velocityEngine.getTemplate(templatePath, encode);
StringWriter writer = new StringWriter();
template.merge(new VelocityContext(objectMap), writer);
render = writer.getBuffer().toString();
writer.close();
} catch (IOException e) {
System.out.println("根据模版引擎生成目标失败");
e.printStackTrace();
} finally {
return render;
}
}
private static VelocityEngine initVelocityEngine() {
Properties p = new Properties();
p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
p.setProperty("file.resource.loader.path", "");
p.setProperty("UTF-8", encode);
p.setProperty("input.encoding", encode);
p.setProperty("file.resource.loader.unicode", "true");
return new VelocityEngine(p);
}
}
- 发送邮件
/**
* 发送html邮件
*
* @param host
* @param userName
* @param sercet
* @param from
* @param to
* @param subject
* @param html
*/
public static void sendHtml(String host, String userName, String sercet, String from, String to, String subject, String html) {
try {
//内嵌图片方式1
// URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
// String cid = email.embed(url, "Apache logo");
//内嵌图片方式2
// String htmlEmailTemplate = ".... <img src=\"http://www.apache.org/images/feather.gif\"> ....";
// URL url = new URL("http://www.apache.org");
// ImageHtmlEmail email = new ImageHtmlEmail();
// email.setDataSourceResolver(new DataSourceUrlResolver(url));
HtmlEmail email = new HtmlEmail();
email.setHostName(host);
email.setAuthenticator(new DefaultAuthenticator(userName, sercet));
email.setFrom(from);
if (to.indexOf(",") == -1) {
email.addTo(to);
} else {
List<String> list = Arrays.asList(to.split(","));
for (String s : list) {
email.addTo(s);
}
}
email.setSubject(subject);
// email.setHtmlMsg(html);
email.setCharset("gbk");
email.setMsg(html);
email.send();
} catch (EmailException e) {
e.printStackTrace();
}
}
/**
* 普通文本1
*
* @throws EmailException
*/
public static void sendText(String host, String userName, String sercet, String from, String to, String subject, String text) {
try {
Email email = new SimpleEmail();
email.setHostName(host);
// email.setSmtpPort(465);
// 用户名和密码为邮箱的账号和密码(不需要进行base64编码)
email.setAuthenticator(new DefaultAuthenticator(userName, sercet));
// email.setSSLOnConnect(true);
email.setFrom(from);
if (to.indexOf(",") == -1) {
email.addTo(to);
} else {
List<String> list = Arrays.asList(to.split(","));
for (String s : list) {
email.addTo(s);
}
}
email.setSubject(subject);
email.setMsg(text);
email.send();
} catch (EmailException e) {
e.printStackTrace();
}
}
- 调用
public static void main(String[] args) throws Exception {
String html = "";
System.out.println(html = RenderUtils.getVmRenderString("\\vmtempalte\\vmtpl.vm",
new HashMap<String, Object>() {{
put("var1", "测试");
put("var2", Arrays.asList("555", "5", "6"));
}}
));
MailHelper.sendHtml(BianMailDto.builder()
.host("smtp.163.com")
.userName("邮箱账号")
.sercet("邮箱授权码")
.from("发送者")
//逗号分隔发送多位
.to("接受者")
.subject("测试标题")
.html(html).build());
}