1-邮件发送需要引入spring-boot-starter-mail
pm.xml中添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2-springboot自动配置MailSenderAutoConfiguration
3-定义MailProperties内容,配置在application.properties中
spring.mail.username=xxx@aliyun.com
#给谁发邮件
spring.mail.password=xxxxx
#阿里云的smtp授权码就是密码
spring.mail.host=smtp.aliyun.com
#阿里云邮箱smtp服务器地址
生成授权码
开启服务
4-自动装配JavaMailSender
测试类中写入
package com.example.springboottask;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
@SpringBootTest
class SpringbootTaskApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
//邮件设置
message.setSubject("通知-今晚开会");
message.setText("今晚7:30开会");
message.setTo("xxx@qq.com"); //可以设置多个,给哪个邮箱发
message.setFrom("xxx@aliyun.com"); //用这个邮箱发送邮件
mailSender.send(message);
}
}
5-测试邮件发送
可能需要开启ssl
6-发送复杂的消息邮件
测试类中添加方法
@Test
void test02() throws Exception {
//创建一个复杂的消息邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//邮件设置
helper.setSubject("通知-今晚开车");
helper.setText("<b style='color:red'>今晚8:30开会</b>",true);
helper.setTo("986588471@qq.com"); //可以设置多个
helper.setFrom("prettypretty@aliyun.com");
//上传文件
helper.addAttachment("1.jpg",new File("C:\\Users\\Administrator\\Downloads\\b216b5dbb62f9ea5920f32836fbfc46c.jpg"));
helper.addAttachment("2.jpg",new File("C:\\Users\\Administrator\\Downloads\\b216b5dbb62f9ea5920f32836fbfc46c.jpg"));
mailSender.send(mimeMessage);
}
运行测试方法