1. 构建环境
在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>
在application.properties
中添加以下依赖:
spring.mail.host=smtp.gmail.com #以Gmail为例
spring.mail.port=587
spring.mail.username=邮箱用户名
spring.mail.password=邮箱密码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
此处可能会遇到Gmail的权限认证问题,需要开启权限许可。
至此,环境构建完毕。
2. 写一个工具类
写一个用于发送邮件的工具类:
@Component
public class EmailTool {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String senderMailAddress;
@Autowired
private TemplateEngine templateEngine;
public void sendSimpleMail(Map