首先,导入springboot的邮箱依赖,版本号可填可不填。
<!--邮件服务-->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
使用基础的springboot3的mail配置,必须遵循以下配置文件架构。
其中邮箱配置信息至少需要三条,否则自动注入会出现无法找到对应的bean问题。
一般情况下,不需要填写邮箱发信端口。
需要填入的基础配置文件为——
spring:
username:邮箱用户名
password:邮箱授权密码
host:邮箱发件地址
简单邮件的发送测试类如下,此处邮箱使用的功能为找回密码,故邮箱标题和正文直接保存配置文件的模版,如需要修改可自行编辑
@SpringBootTest
@ActiveProfiles("dev")
public class MailTest {
@Autowired
private JavaMailSender sender;
@Value("${spring.mail.from}")
private String from ;
@Value("${spring.mail.content}")
private String content ;
@Value("${spring.mail.subject}")
private String subject ;
@Test
public void testMail() {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setSubject(subject);
mail.setText(content);
mail.setTo(from);
mail.setFrom(from);
sender.send(mail);
System.out.println("发送成功");
}
}
注意:配置文件中,第三方邮箱不需要填写邮箱的发信端口,如25或者465,否则会导致java虚拟机无法连接邮箱。
