Spring Boot 发送邮件全解析

1.前言

电子邮件虽然近几年有点“退火”,但是在开发中依然有举足轻重的地位。在比较正式的场合我们依然通过电子邮件来传递信息和回执。今天我们就来学一下如何在 Spring Boot 下发送电子邮件。

2. 依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-mail</artifactId>
  4. </dependency>

3. Service

  1. @Service
  2. public class EmailService {
  3. @Autowired
  4. private JavaMailSenderImpl javaMailSender;
  5. //简单邮件测试
  6. public void sendSimple(){
  7. SimpleMailMessage message = new SimpleMailMessage();
  8. message.setSubject("email测试");
  9. message.setText("邮件测试内容");
  10. message.setTo("xxx@sohu.com");
  11. message.setFrom("xxx@sohu.com");
  12. javaMailSender.send(message);
  13. }
  14. //复杂邮件测试
  15. public void sendComplicated() throws MessagingException {
  16. //创建一个复杂的消息邮件
  17. MimeMessage mimeMessage = javaMailSender.createMimeMessage();
  18. //用MimeMessageHelper来包装MimeMessage
  19. MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
  20. mimeMessageHelper.setSubject("email测试");
  21. mimeMessageHelper.setText("邮件测试内容");
  22. mimeMessageHelper.setTo("fanqixxxx@vip.qq.com");
  23. mimeMessageHelper.setFrom("fanqixxxx@163.com");
  24. mimeMessageHelper.addAttachment("meinv.jpg",new File("D:\\meinv.jpg"));
  25. javaMailSender.send(mimeMessage);
  26. }

4. application.properties

  1. #email
  2. spring.mail.username=dddddf@sohu.com
  3. #spring.mail.password 填写授权码
  4. spring.mail.password=ddddd
  5. #spring.mail.host 填写邮箱供应的SMTP地址
  6. spring.mail.host=smtp.sohu.com
  7. spring.mail.properties.mail.smtp.ssl.enable=true