一:导入pom依赖
<!--mail依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
二:配置application.properties中邮件相关属性
这里的密码是加密的,需要登录发送邮件账户,在设置中开启pop3/smtp服务(我用的是qq邮箱),即可自动生成加密的密码
三:在测试类中实现发送邮件功能
@SpringBootTest
class SpringbootAsyncApplicationTests {
@Autowired
JavaMailSenderImpl javaMailSender; //用于发送邮件
@Test
void contextLoads() {
//一个简单邮件
SimpleMailMessage simpleMail = new SimpleMailMessage();
simpleMail.setSubject("zym你好"); //邮件主题
simpleMail.setText("are you OK?"); //邮件内容
simpleMail.setTo("691639910@qq.com"); //接收者
simpleMail.setFrom("691639910@qq.com"); //发送者
javaMailSender.send(simpleMail);
}
@Test
void contextLoads2() throws MessagingException {
//一个复杂邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//用MimeMessageHelper组装复杂邮件,第二个参数为true,可以发送附件
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//正文,可以发送html文本,需要第二个参数为true
helper.setSubject("zym你好");
helper.setText("<p style='color:red'>春暖花开</p>",true);
//附件
helper.addAttachment("1.png", new File("C:\\Users\\LENOVO\\Pictures\\1.png"));
helper.setTo("691639910@qq.com"); //接收者
helper.setFrom("691639910@qq.com"); //发送者
javaMailSender.send(mimeMessage);
}
}