Spring Boot 发送邮件
1. 邮箱设置
启用客户端SMTP服务。
2. Spring Email
-
导入 jar 包:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> <version>2.3.2.RELEASE</version> </dependency>
-
邮箱参数配置:
# MailProperties # 邮箱域名(我这里用的是新浪邮箱) spring.mail.host=smtp.sina.com # 邮箱端口 spring.mail.port=465 # 邮箱账号 spring.mail.username= # 邮箱密码 spring.mail.password= # 协议 spring.mail.protocol=smtps # 发送邮件采用ssl安全连接 spring.mail.properties.mail.smtp.ssl.enable=true
-
使用JavaMailSender发送邮件:
先新建一个MailClient工具类:
@Component public class MailClient { private static final Logger logger = LoggerFactory.getLogger(MailClient.class); @Autowired private JavaMailSender mailSender; //发送人,即配置文件中的邮箱账号 @Value("${spring.mail.username}") private String from; /** * * @param to 收件人 * @param subject 邮件标题 * @param content 邮件内容 */ public void sendMail(String to,String subject,String content) { try { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); // 如果不加第二个参数true,就会认为只是普通文本 // 加了参数true,就能识别HTML文本,支持发送HTML文件 helper.setText(content,true); mailSender.send(helper.getMimeMessage()); } catch (MessagingException e) { logger.error("发送邮件失败:" + e.getMessage()); } } }
测试类:
@RunWith(SpringRunner.class) @SpringBootTest @ContextConfiguration(classes = Application.class) public class MailTests { @Autowired private MailClient mailClient; @Test public void testTextMail(){ mailClient.sendMail("此处为收件人邮件","此处为邮件标题","此处为邮件正文"); } }
3. 模板引擎
使用Thymeleaf发送HTML邮件:
新建一个Thymeleaf在templates文件夹下的mail文件夹下命名为demo.html(对应测试类process方法的第一个参数)。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>使用Thymeleaf发送HTML邮件</title>
</head>
<body>
<p>欢迎你,<span style="color: red;" th:text="${username}"></span></p>
</body>
</html>
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = Application.class)
public class MailTests {
@Autowired
private TemplateEngine templateEngine;
@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("此处为收件人邮箱","此处为邮件标题",content);
}
}