发送邮件
由于项目的注册功能需要向注册用户发送激活邮件,先完成Spring Email邮件功能的测试。
1.邮箱设置
需要启用客户端SMTP服务。
2.Spring Email
2.1导入jar依赖包
在pom.xml添加如下依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
2.2在配置文件中对邮箱参数进行配置
application.properties添加与spring发送邮件相关的配置。值得注意的是,不同邮件系统所需的配置不同。【网易邮箱和新浪邮箱properties配置不同,网易邮箱需要授权码。】
# MailProperties gmail和163邮箱配置不一致,需要注意
spring.mail.host=smtp.163.com
#spring.mail.port=465
spring.mail.username=xxxxxxx@163.com
spring.mail.password=xxxxxxxxxxxxx
#spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
#spring.mail.properties.mail.smtp.ssl.enable=tr
3.测试邮件功能
在test包中创建MailTests测试类,代码如下。
package com.gerrard.community;
import com.gerrard.community.util.MailClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests {
@Autowired
private MailClient mailClient;
@Autowired
private TemplateEngine templateEngine;
//直接发送文字信息
@Test
public void testTextMail() {
mailClient.sendMail("xxxxx@qq.com", "TEST", "Welcome.");
}
//发送动态网页
@Test
public void testHtmlMail() {
Context context = new Context();
context.setVariable("username", "sunday"); //将变量内容填充到模板中
String content = templateEngine.process("/mail/demo", context);
System.out.println(content);
mailClient.sendMail("xxxxxx@qq.com", "HTML", content);
}
}
Thymeleaf HTML模板内容:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件示例</title>
</head>
<body>
<p>欢迎你, <span style="color:red;" th:text="${username}"></span>!</p>
</body>
</html>
4.功能演示
1.先测试发送文本邮件功能,运行testTextMail方法,目标邮箱成功收到了来自spring.mail.host端发送的测试文本邮件。
2.在测试结合Thymeleaf发送HTML邮件,运行testHtmlMail方法,目标邮箱也成功收到了来自spring.mail.host端发送的测试HTML邮件。