Java Mail+Thymeleaf模板引擎实现发送HTML格式邮件
基于Spring boot 1.5,Spring boot 2.x请使用Spring boot mail
1.依赖坐标
// buildscript 代码块中脚本优先执行
buildscript {
//springBootVersion = '1.5.2.RELEASE' 经典稳定版本
// ext 用于定义动态属性
ext {
springBootVersion = '1.5.2.RELEASE'
}
// 自定义 Thymeleaf 和 Thymeleaf Layout Dialect 的版本
ext['thymeleaf.version'] = '3.0.3.RELEASE'
ext['thymeleaf-layout-dialect.version'] = '2.2.0'
// 自定义 Hibernate 的版本
ext['hibernate.version'] = '5.2.8.Final'
// 使用了 Maven 的中央仓库(你也可以指定其他仓库)
repositories {
//mavenCentral()
maven {
url 'http://maven.aliyun.com/nexus/content/groups/public/'
}
}
// 依赖关系
dependencies {
// classpath 声明说明了在执行其余的脚本时,ClassLoader 可以使用这些依赖项
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
// 使用插件
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
// 打包的类型为 jar,并指定了生成的打包的文件名称和版本
jar {
baseName = 'blog-search'
version = '1.0.0'
}
// 指定编译 .java 文件的 JDK 版本
sourceCompatibility = 1.8
// 默认使用了 Maven 的中央仓库。这里改用自定义的镜像库
repositories {
//mavenCentral()
maven {
url 'http://maven.aliyun.com/nexus/content/groups/public/'
}
}
// 依赖关系
dependencies {
// 该依赖对于编译发行是必须的
compile('org.springframework.boot:spring-boot-starter-web')
// 添加 Thymeleaf 的依赖
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
// 添加 Spring Security 依赖
compile('org.springframework.boot:spring-boot-starter-security')
// 添加 Spring Boot 开发工具依赖
//compile("org.springframework.boot:spring-boot-devtools")
// 添加 Spring Data JPA 的依赖
compile('org.springframework.boot:spring-boot-starter-data-jpa')
// 添加 MySQL连接驱动 的依赖
compile('mysql:mysql-connector-java:6.0.5')
// 添加 Thymeleaf Spring Security 依赖,与 Thymeleaf 版本一致都是 3.x
compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4:3.0.2.RELEASE')
// 添加 Apache Commons Lang 依赖
compile('org.apache.commons:commons-lang3:3.5')
// 添加 Markdown parser 依赖
compile('es.nitaur.markdown:txtmark:0.16')
// 添加 Spring Data Elasticsearch 的依赖
compile('org.springframework.boot:spring-boot-starter-data-elasticsearch')
// 添加 JNA 的依赖
compile('net.java.dev.jna:jna:4.3.0')
// 该依赖对于编译测试是必须的,默认包含编译产品依赖和编译时依
testCompile('org.springframework.boot:spring-boot-starter-test')
/*
FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。
它不是面向最终用户的,而是一个Java类库,是一款可以嵌入所开发产品的组件。
*/
//compile('org.springframework.boot:spring-boot-starter-freemarker')
//添加 JavaMail 发送邮件
compile("javax.mail:javax.mail-api:1.5.6")
compile("com.sun.mail:javax.mail:1.5.6")
//添加Spring Boot Mail 的依赖,注意SpringBoot2.x以上版本
//compile("org.springframework.boot:spring-boot-starter-mail")
}
2.配置文件
#Java Mail
# 邮件服务器地址
mail.host=smtp.qq.com
#发件人邮箱地址
mail.user=***@qq.com
#发件人邮箱密码
mail.password=****
3.邮件工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Map;
import java.util.Properties;
@Component
public class MailTemplateSenderUtils {
@Value("${mail.user}")
private String USER;
@Value("${mail.password}")
private String PASSWORD;
@Value("${mail.host}")
private String HOST;
@Autowired
private TemplateEngine templateEngine;
public Boolean sendMail(Map<String, Object> valueMap) {
try {
final Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", HOST);
// 发件人的账号
props.put("mail.user", USER);
//发件人的密码
props.put("mail.password", PASSWORD);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
// 设置发件人
String username = props.getProperty("mail.user");
InternetAddress form = new InternetAddress(username);
message.setFrom(form);
// 设置收件人
String to = (String) valueMap.get("to");
InternetAddress toAddress = new InternetAddress(to);
message.setRecipient(Message.RecipientType.TO, toAddress);
// 设置邮件标题
String title = (String) valueMap.get("title");
message.setSubject(title);
// 设置邮件的内容体
Context context = new Context();
context.setVariables(valueMap);
String content = templateEngine.process("MailTemplate", context);
message.setContent(content, "text/html;charset=UTF-8");
// 发送邮件
Transport.send(message);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}