springboot自动配置包中MailSenderAutoConfiguration通过@Import注解向容器中导入了MailSenderJndiConfiguration,而MailSenderJndiConfiguration向容器中导入了JavaMailSenderImpl类,我们可以使用该类发送邮件
首先登录自己的qq邮箱,进入 设置 - 账户 开启所有服务
点POP3的开启获取授权码
加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置文件
spring:
mail:
username: 邮箱用户名
password: 邮箱密码或授权码 (建议使用授权码 安全)
host: smtp.qq.com
port: 465
protocol: smtps
自动注入
@Autowired
private JavaMailSenderImpl javaMailSender;
简单邮件发送
SimpleMailMessage message = new SimpleMailMessage();
//设置主题和内容
message.setSubject("今天开会");
message.setText("物质楼555开会,不要迟到");
//设置发送方和接收方
message.setTo("xxx@163.com");
message.setFrom("xxx@qq.com");
javaMailSender.send(message);
复杂邮件发送
带有附件或html页面的邮件
两个设置
new MimeMessageHelper(message,true) 设置multipart=true,开启对内联元素和附件的支持
helper.setText("xxxx",true) html=ture,设置content type=text/html,默认为text/plain
MimeMessage message = javaMailSender.createMimeMessage();
//multipart=true
//开启对内联元素和附件的支持
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setSubject("今天开会");
//html=ture
//设置content type=text/html,默认为text/plain
helper.setText("<b style='color:red'>物质楼555开会,不要迟到</b>",true);
helper.setFrom("hongshengmo@163.com");
helper.setTo("1043245239@qq.com");
//设置附件
helper.addAttachment("2.png",new File("D:\\Works\\Note\\images\\图片2.png"));
helper.addAttachment("3.png",new File("D:\\Works\\Note\\images\\图片3.png"));
javaMailSender.send(message);