1.添加依赖
<!--mail-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置文件application.properties
#邮件配置
spring.mail.host=smtp.qq.com
#默认编码格式,默认utf-8
spring.mail.default-encoding=utf-8
#发件邮箱
spring.mail.username=2572037297@qq.com
#邮箱授权码
spring.mail.password=ssflpcyntcmxdibc
3.发送简单邮件
@Autowired
JavaMailSender mailSender;
//读取配置文件的发件人
@Value("${spring.mail.username}")
private String from ;
@Test
public void sendEmail(){
//自动装配就不用new了
//MailSender mailSender = new JavaMailSenderImpl();
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//发件人
simpleMailMessage.setFrom(from);
//发件内容
simpleMailMessage.setText("祝你幸福");
//发送给谁
simpleMailMessage.setTo("whh1874@163.com");
//邮件主题
simpleMailMessage.setSubject("测试");
mailSender.send(simpleMailMessage);
}
4.发送html格式的邮件
@Autowired
JavaMailSender mailSender;
//读取配置文件的发件人
@Value("${spring.mail.username}")
private String from ;
@Test
public void sendHTMLEmail() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
//此处multipart必须设置为true
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
mimeMessageHelper.setFrom(from);
//此处true为解析html标签,设置为false不生效
mimeMessageHelper.setText("<h1>这是一封html格式的邮件</h1>",true);
mimeMessageHelper.setTo("whh1874@163.com");
mimeMessageHelper.setSubject("测试html格式邮件");
mailSender.send(mimeMessage);
}
5.发送邮件带附件
@Autowired
JavaMailSender mailSender;
//读取配置文件的发件人
@Value("${spring.mail.username}")
private String from ;
@Test
public void testSendFileEmail() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setTo("whh1874@163.com");
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setText("一封自拍");
FileSystemResource fileSystemResource = new FileSystemResource(new File("文件路径"));
mimeMessageHelper.addAttachment("mhb.jpg",fileSystemResource);
mimeMessageHelper.setSubject("这是HTML邮件");
mailSender.send(mimeMessage);
}