方案实现

1、引用依赖

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

2、代码实现

此处以从**QQ邮箱**发送为例

  1. public void send() throws MessagingException {
  2. JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
  3. javaMailSender.setHost("smtp.qq.com");//发邮件主机地址
  4. javaMailSender.setPort(587);//发邮件端口
  5. javaMailSender.setUsername("314850828@qq.com");//发件人用户名。基本与发件人邮箱地址相同
  6. javaMailSender.setPassword("gbpzwiprmqcbcace"); //授权码。这个不是你的QQ密码
  7. javaMailSender.setDefaultEncoding("UTF-8");
  8. MimeMessage mimeMessage = javaMailSender.createMimeMessage();
  9. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  10. helper.setSubject("Test Subject");
  11. helper.setFrom("314850828@qq.com"); //发件人邮箱地址
  12. helper.setTo("test@sina.com");
  13. helper.setSentDate(new Date());
  14. helper.setText("test la la la ", true);
  15. javaMailSender.send(mimeMessage);
  16. }