导入maven依赖
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置邮箱属性
application.properties
#配置邮箱属性
spring.mail.host=smtp.qq.com
#个人邮箱的用户名和密码(密码我们使用加密后的授权码)
spring.mail.username=1601051004@qq.com
spring.mail.password=thjiniowsetfgfgd
spring.mail.default-encoding=UTF-8
发送纯文本邮件
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("1601051004@qq.com");
message.setTo("1601051004@qq.com");
message.setSubject("熊二吃屁的测试");
message.setText("熊二吃屁真帅");
mailSender.send(message);
}
发送富文本邮件
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setSubject("熊二熊二");
helper.setText("<p style='color:red'>熊二真帅</p>",true);
// 添加附件
helper.addAttachment("bear.jpg",new File("C:\\Users\\BOSS\\Pictures\\Saved Pictures\\ball.jpg"));
helper.setFrom("1601051004@qq.com");
helper.setTo("1601051004@qq.com");
mailSender.send(message);
}