设置邮箱

这里以QQ邮箱为例,进入设置-帐户:
image.png
开始POP3/SMTP服务(这一步会得到一个密码,下面会用到):
image.png

编写代码

增加依赖pom.xml:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-mail</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-web</artifactId>
  8. </dependency>

创建配置文件application.yml:

  1. spring:
  2. mail:
  3. # qq邮箱用这个
  4. host: smtp.qq.com
  5. port: 587
  6. # 邮箱号
  7. username: xxxx@qq.com
  8. # 开启POP3/SMTP时得到的密码
  9. password: xxxxxx
  10. default-encoding: utf-8
  11. properties:
  12. mail:
  13. debug: true

创建控制器TestController.java:

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.mail.MailException;
  3. import org.springframework.mail.SimpleMailMessage;
  4. import org.springframework.mail.javamail.JavaMailSender;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. @RestController
  8. public class TestController {
  9. @Autowired
  10. private JavaMailSender mailSender;
  11. @GetMapping("sendMail")
  12. public String sendMail() {
  13. // 创建简单邮件消息
  14. SimpleMailMessage message = new SimpleMailMessage();
  15. // 谁发的
  16. message.setFrom("xxx@qq.com");
  17. // 谁要接收
  18. message.setTo("xxx@qq.com");
  19. // 邮件标题
  20. message.setSubject("subject");
  21. // 邮件内容
  22. message.setText("content");
  23. try {
  24. mailSender.send(message);
  25. return "发送普通邮件成功";
  26. } catch (MailException e) {
  27. e.printStackTrace();
  28. return "普通邮件方失败";
  29. }
  30. }
  31. }

访问sendMail控制器,发送成功:
image.png