1、导入邮件发送Maven依赖
<!--邮件发送
MailProperties类中查看配置信息
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、在application.properties中设置发送基本参数
#设置邮箱发送配置信息
spring.mail.username=xxxxxxxxxx@qq.com
#QQ发送需要去QQ邮件获取授权码作为密码
spring.mail.password=xxxxxx
#设置邮件服务器
spring.mail.host=smtp.qq.com
#开启 QQ加密授权验证
spring.mail.properties.mail.smtp.ssl.enable=true
3、测试发送功能
简单邮件发送
@Autowired
JavaMailSenderImpl mailSender;
//简单的邮件
@Test
public void MailSendTest(){
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("来自JAVA SrpingBoot 的邮件");
message.setText("我自己发给自己的邮件");
message.setTo("xxxxxxx@139.com");
message.setFrom("xxxxx@qq.com");
mailSender.send(message);
}
复杂邮件发送
//复杂的邮件
@Test
public void MailSend() throws MessagingException {
//一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
helper.setSubject("你好呀,我");
//设置支持html
helper.setText("<p style='color:red'>来自远方的邮件</p>",true);
//附件
helper.addAttachment("jianli.doc",new File("C:\Users\***\Desktop\4562.doc"));
//
helper.setTo("****@139.com");
helper.setFrom("****@qq.com");
mailSender.send(mimeMessage);
}