Spring Boot

Spring Boot 的 mail starter 读取五个属性,把它们指向沙箱即可。

前提条件

  • Spring Boot 2.7 或更高版本
  • spring-boot-starter-mail

1添加 starter

pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2配置邮件发送器

application.properties
spring.mail.host=smtp.mailclutch.com
spring.mail.port=587
spring.mail.username=mc_0000000000000000
spring.mail.password=pw_0000000000000000
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

如果生产环境的 profile 有自己的邮件服务器,就把这段配置放在 application-staging.properties 里。

3发送一封测试邮件

@Autowired
private JavaMailSender mailSender;

public void sendTest() {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom("staging@example.com");
    message.setTo("anyone@example.com");
    message.setSubject("Sandbox check");
    message.setText("Hello from Spring Boot.");

    mailSender.send(message);
}

看着它到达

打开沙箱,邮件已经在里面:渲染后的 HTML、纯文本、原始源码、附件,以及 SPF、DKIM 和 DMARC 的检查结论。页面实时更新,可以开着它放在终端旁边。

无论发给哪个地址,邮件都不会被继续投递;注册账号认领这个沙箱,它就会保留下来。

正在等待你的邮件

发给任何地址都行,邮件会停在这里,不会继续投递。沙箱捕获的邮件保留 24 小时。

深入了解

  • @Async 与错误上报

    标注了 @Async 的发信方法会在另一个线程里失败,异常根本到不了你的请求。验证配置期间请同步发送。

  • spring.mail.test-connection

    spring.mail.test-connection=true 会在应用启动时就连接沙箱,主机、端口或凭据写错时启动直接失败,而不是等到发第一封邮件才暴露。

官方文档Spring Boot — Sending Email (在新标签页中打开)