1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、开启邮箱(这边使用的是126,QQ等其它同理)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3195a3841a2c17980789fb36fba5d694.png)
3、application.properties配置
# 你的邮箱/或者一般企业中有一个公共使用的邮箱
spring.mail.username=xxxxx@126.com
# 使用上面给的授权密码
spring.mail.password=JXSUIDHJWYQNZXHE
#QQ的话是 smtp.qq.com 163: smtp.163.com
spring.mail.host=smtp.126.com
#QQ的话还需要开启加密验证
#spring.mail.properties.mail.smtp.ssl.enable=true
4、实现
@SpringBootTest
class DemoApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject("主题内容测试");
simpleMailMessage.setText("测试212121212");
simpleMailMessage.setTo("xxx@126.com");
simpleMailMessage.setFrom("xxx@126.com");
mailSender.send(simpleMailMessage);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/877ae1bda834eac48580f45360130838.png)
@SpringBootTest
class DemoApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("复杂内容测试");
helper.setText("<p style='color:red'>复杂内容测试</p>",true);
helper.addAttachment("1.jpg",new File("C:\\Users\\Admin\\Pictures\\Saved Pictures\\1.jpg"));
helper.setTo("xxx@126.com");
helper.setFrom("xxx@126.com");
mailSender.send(mimeMessage);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6ae5e0d577caa61836e473947ffa7633.png)