[关闭]
@File 2019-09-27T01:51:25.000000Z 字数 1316 阅读 132

java 发送邮件

java


相关网址

POP3/IMAP/SMTP 协议
spring-boot发邮件

开启服务拿到授权码

授权码:作为配置时必须的密码
收发流程:
image_1dl92rrotfibpf05r2ekh1lls1g.png-110.6kB

spring-boot

1. 依赖

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

2. yml配置

  1. spring:
  2. # 配置发送方信息
  3. mail:
  4. # 邮箱类型(当前为qq邮箱)
  5. # qq企业邮箱:smtp.exmail.qq.com
  6. # 阿里云个人邮箱:smtp.aliyun.com
  7. # 163个人邮箱:smtp.163.com
  8. # 163邮箱企业:smtp.qiye.163.com
  9. host: smtp.qq.com
  10. # 邮箱账号(重点修改)
  11. username: 88888888@qq.com
  12. # 授权码,非登录密码(重点修改)
  13. password: z5qc4sn1kyd7jva2u5bb4b6a0
  14. # 常用配置
  15. properties:
  16. mail:
  17. smtp:
  18. auth: true
  19. timeout: 25000
  20. ssl:
  21. enable: true

3. 封装成一个类

  1. @Component
  2. public class MailUtil {
  3. /**
  4. * 发邮件类
  5. */
  6. @Resource
  7. private JavaMailSenderImpl mailSender;
  8. /**
  9. * 读取配置中的发送方邮箱
  10. */
  11. @Value("${spring.mail.username}")
  12. private String from;
  13. /**
  14. * 发送邮件
  15. * @param toMail 接收方email
  16. * @param subject 邮件标题
  17. * @param content 邮件内容
  18. * @return 是否成功发送
  19. */
  20. public boolean send(String toMail, String subject, String content) {
  21. // 邮件配置类
  22. SimpleMailMessage message = new SimpleMailMessage();
  23. // 发件方邮箱
  24. message.setFrom(from);
  25. // 收件方邮箱
  26. message.setTo(toMail);
  27. // 邮件标题
  28. message.setSubject(subject);
  29. // 邮件内容
  30. message.setText(content);
  31. try {
  32. mailSender.send(message);
  33. // 发送成功
  34. return true;
  35. }catch (Exception e) {
  36. // 发送失败
  37. // e.printStackTrace();
  38. return false;
  39. }
  40. }
  41. }

4. 调用

  1. @Service
  2. public class MailServiceImpl implements MailService {
  3. @Resource
  4. private MailUtil mailUtil;
  5. @Override
  6. public boolean sendMail() {
  7. return mailUtil.send("邮箱地址","标题","正文");
  8. }
  9. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注