Spring Boot 发送邮件

待我称王封你为后i 2023-01-18 09:22 97阅读 0赞

第一步:引入Spring Boot整合邮件的依赖

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

第二步:例如以网易云邮箱为例,在设置中开通pop3服务并获取一个授权码

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3lfYmNjbDI3_size_16_color_FFFFFF_t_70

第三步:yml配置文件中添加下述配置

  1. spring:
  2. mail:
  3. host: smtp.163.com
  4. port: 25
  5. username: 邮箱账号
  6. password: 生成的授权码
  7. default-encoding: utf-8
  8. properties:
  9. mail:
  10. smtp:
  11. auth: true
  12. starttls:
  13. enable: true
  14. required: true

第四步:构建实体类

  1. import lombok.Data;
  2. @Data
  3. public class MailDTO {
  4. //接受邮件的邮箱账户
  5. private String mailAccount;
  6. //邮箱标题
  7. private String title;
  8. //要发送的内容
  9. private String content;
  10. }

第五步:构建发送邮件的实现

  1. import com.bc.work.dto.MailDTO;
  2. import com.bc.work.service.MailService;
  3. import org.springframework.mail.MailSender;
  4. import org.springframework.mail.SimpleMailMessage;
  5. import javax.annotation.Resource;
  6. /**
  7. * 邮箱发送实现类
  8. */
  9. @Service
  10. @Component
  11. public class MailServiceImpl implements MailService {
  12. @Resource
  13. private MailSender mailSender;
  14. @Override
  15. public void send(MailDTO mailDTO) {
  16. MailDTO mailDTO=new MailDTO();
  17. mailDTO.setMailAccount("xxxx@163.com");
  18. mailDTO.setTitle("主题");
  19. mailDTO.setContent("内容");
  20. //new 一个简单邮件消息对象
  21. SimpleMailMessage message = new SimpleMailMessage();
  22. //和配置文件中的的username相同,相当于发送方
  23. message.setFrom("xxxx@163.com");
  24. //收件人邮箱
  25. message.setTo(mailDTO.getMailAccount());
  26. //标题
  27. message.setSubject(mailDTO.getTitle());
  28. //正文
  29. message.setText(mailDTO.getContent());
  30. //发送
  31. mailSender.send(message);
  32. }
  33. }

发表评论

表情:
评论列表 (有 0 条评论,97人围观)

还没有评论,来说两句吧...

相关阅读