使用 SpringBoot 发送邮件
使用 SpringBoot 发送邮件
思路:使用 thymeleaf 解析并渲染 html 模版,将 html 内容作为邮件内容发送
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
配置文件
server.port=8082
spring.mail.host=smtp.qq.com
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
spring.mail.password=授权码
spring.mail.username=xxxx@qq.com
spring.mail.port=587
spring.mail.properties.mail.stmp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
EmailSender.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
@Component
public class EmailSender {
@Autowired
JavaMailSender javaMailSender;
@Autowired
MailProperties mailProperties;
@Autowired
TemplateEngine templateEngine;
public void sendSignUpCaptcha(String mailAddress, String code, Integer sec) {
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg);
try {
//设置邮件元信息
helper.setTo("xxx@163.com");
helper.setFrom(mailProperties.getUsername());
helper.setSubject("验证码");
helper.setSentDate(new Date());
//模板渲染
Context context = new Context();
context.setVariable("name", "engureguo");
context.setVariable("code", "833391");
String mail = templateEngine.process("mail", context);
helper.setText(mail, true);
javaMailSender.send(msg);
System.out.println("邮件发送成功!");
} catch (MessagingException e) {
System.out.println("邮件发送失败" + e.getMessage());
}
}
}
邮件 html 模版:templates/mail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎注册 abc 网站!</title>
</head>
<style>
.big-font {
font-size: 25px;
}
.warning {
color: red;
background-color: bisque;
display: inline;
}
</style>
<body>
<h3>亲爱的 [[${name}]],欢迎注册 abc 网站!</h3>
<p>您的<b>注册验证码</b>是:<b class="big-font"> [[${code}]] </b></p>
<p class="warning">如果您并没有注册 abc 网站,请忽略该邮件!</p>
</body>
</html>
沉舟侧畔千帆过,病树前头万木春。