当前位置:   article > 正文

springboot整合邮箱功能一(实战)_springboot 适配所有的邮箱

springboot 适配所有的邮箱

背景介绍

邮件发送其实是一个非常常见的需求,用户注册,找回密码、校验码等地方。如果使用短信还需缴费。这里发送者邮箱选用了163邮箱。

1、pom.xml文件的引用

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <!--<version>2.7.11</version>-->
  10. <version>2.5.5</version>
  11. <relativePath/> <!-- lookup parent from repository -->
  12. </parent>
  13. <properties>
  14. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  16. <java.version>1.8</java.version>
  17. <project-name>spring-boot-email</project-name>
  18. <maven.compiler.source>8</maven.compiler.source>
  19. <maven.compiler.target>8</maven.compiler.target>
  20. </properties>
  21. <groupId>org.example</groupId>
  22. <artifactId>${project-name}</artifactId>
  23. <version>1.0-SNAPSHOT</version>
  24. <name>${project-name}</name>
  25. <description>${project-name}</description>
  26. <dependencies>
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-mail</artifactId>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.springframework.boot</groupId>
  33. <artifactId>spring-boot-starter-test</artifactId>
  34. <scope>test</scope>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-web</artifactId>
  39. </dependency>
  40. <!-- ================= 应用 ================== -->
  41. <!-- thymeleaf模板 -->
  42. <dependency>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  45. <!--<version>2.3.12.RELEASE</version>-->
  46. </dependency>
  47. <dependency>
  48. <groupId>com.alibaba.fastjson2</groupId>
  49. <artifactId>fastjson2</artifactId>
  50. <version>2.0.25</version>
  51. </dependency>
  52. <dependency>
  53. <groupId>org.apache.commons</groupId>
  54. <artifactId>commons-lang3</artifactId>
  55. </dependency>
  56. <dependency>
  57. <groupId>com.google.guava</groupId>
  58. <artifactId>guava</artifactId>
  59. <version>31.1-android</version>
  60. </dependency>
  61. </dependencies>
  62. <build>
  63. <plugins>
  64. <plugin>
  65. <groupId>org.springframework.boot</groupId>
  66. <artifactId>spring-boot-maven-plugin</artifactId>
  67. <version>2.7.1</version>
  68. <configuration>
  69. <excludes>
  70. <exclude>
  71. <groupId>org.projectlombok</groupId>
  72. <artifactId>lombok</artifactId>
  73. </exclude>
  74. </excludes>
  75. </configuration>
  76. </plugin>
  77. </plugins>
  78. </build>
  79. </project>

2、yml配置文件中的配置

  1. server:
  2. port: 8000
  3. max-http-header-size: 8192
  4. servlet:
  5. encoding:
  6. charset: UTF-8
  7. force: true
  8. enabled: true
  9. #配置日志
  10. logging:
  11. level:
  12. root: info
  13. spring:
  14. application:
  15. name: spring-boot-email
  16. mvc.async.request-timeout: 20000
  17. mail:
  18. # host: "smtp.163.com" # 发件服务器地址
  19. # port: 25 # 常用邮件端口25、109、110、143、465、995、993、994 如果开启了SSL安全则使用对应的端口号,25为非加密端口号
  20. # username: admin@163.com # 发送邮件的账号
  21. # password: 123456 # 配置密码,注意,不是真正的密码,而是刚刚申请到的授权码
  22. # default-encoding: utf-8 # 设置编码
  23. host: smtp.exmail.qq.com
  24. port: 465
  25. username: admin@xxx.cn
  26. password: 123123
  27. default-encoding: utf-8 # 设置编码
  28. protocol: smtp
  29. properties: # 设置邮件超时时间防止服务器阻塞
  30. timeout: 5000
  31. connection-timeout: 5000
  32. write-timeout: 5000
  33. mail:
  34. debug: true # 表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
  35. # 官方建议使用 465 端口,而 465 端口是 SSL 协议的,所以不仅要换端口,
  36. # 还需要进行 SSL 协议替换。下面是在 application.properties 进行的邮件发送相关配置,
  37. smtp:
  38. socketFactory:
  39. port: 465
  40. #socketFactoryClass: javax.net.ssl.SSLSocketFactory #配饰 SSL 加密工厂
  41. ssl:
  42. enable: true

3、EmailController

  1. package org.example.controller;
  2. import org.example.entity.EmailModel;
  3. import org.example.service.EmailService;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.PostMapping;
  8. import org.springframework.web.bind.annotation.RequestBody;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import javax.mail.MessagingException;
  12. /**
  13. * @description:
  14. */
  15. @RestController
  16. public class EmailController {
  17. Logger log = LoggerFactory.getLogger(getClass());
  18. @Autowired
  19. EmailService emailService;
  20. @PostMapping("sendModleMail")
  21. public String sendModleMail(@RequestBody EmailModel model) throws MessagingException {
  22. emailService.sendModleMail(model);
  23. return "success!";
  24. }
  25. }

4、EmailService

  1. package org.example.service;
  2. import org.example.entity.EmailModel;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.mail.javamail.JavaMailSender;
  7. import org.springframework.mail.javamail.MimeMessageHelper;
  8. import org.springframework.scheduling.annotation.EnableAsync;
  9. import org.springframework.stereotype.Service;
  10. import javax.annotation.Resource;
  11. import javax.mail.MessagingException;
  12. import javax.mail.internet.MimeMessage;
  13. import java.io.File;
  14. import java.util.Date;
  15. /**
  16. * @author Administrator
  17. */
  18. @Service
  19. @EnableAsync
  20. public class EmailService {
  21. Logger log = LoggerFactory.getLogger(getClass());
  22. /**
  23. * 发送者邮箱
  24. */
  25. @Value("${spring.mail.username}")
  26. public String MAIL_USERNAME;
  27. /**
  28. * JavaMailSender类的对象,是springboot自动装配的
  29. */
  30. @Resource
  31. private JavaMailSender javaMailSender;
  32. public void sendModleMail(EmailModel model) throws MessagingException {
  33. MimeMessage mimeMessage = javaMailSender.createMimeMessage();
  34. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  35. helper.setSubject(model.getSubject()); // 邮件标题
  36. helper.setFrom(MAIL_USERNAME); // 发送者邮箱
  37. helper.setTo(model.getRecipientMailbox()); // 收件人邮箱
  38. if (model.getCcMailbox() != null && model.getCcMailbox().length != 0) {
  39. helper.setCc(model.getCcMailbox()); // 抄送人
  40. }
  41. if (model.getBccMailbox() != null && model.getBccMailbox().length != 0) {
  42. helper.setBcc(model.getBccMailbox()); // 加密抄送
  43. }
  44. helper.setSentDate(new Date()); // 发送日期
  45. helper.setText(model.getSendContent()); // 发送内容
  46. if (!model.getEnclosures().isEmpty()) {
  47. log.info("-------[Iterator循环遍历]通过keySet取出map数据---------");
  48. for (String key : model.getEnclosures().keySet()) {
  49. helper.addAttachment(key, new File(model.getEnclosures().get(key)));// 预览文件
  50. // System.out.println("key值:"+key+" value值:"+model.getEnclosures().get(key));
  51. }
  52. }
  53. // helper.addAttachment("2.jpg", new File("E:\\pic\\2.jpg"));//预览文件
  54. // helper.addInline("p01",new FileSystemResource(new File("E:\\pic\\2.jpg")));//配合前端可以直接预览图片
  55. // helper.addInline("p02",new FileSystemResource(new File("E:\\pic\\2.jpg")));
  56. javaMailSender.send(mimeMessage);
  57. }
  58. }

5、创建发送邮箱EmailModel

  1. package org.example.entity;
  2. /**
  3. * @author 86133 2023-05-08 10:52:59
  4. */
  5. import java.io.Serializable;
  6. import java.util.Map;
  7. public class EmailModel implements Serializable {
  8. /**
  9. * 邮件主题
  10. */
  11. private String subject;
  12. /**
  13. * 收件人邮箱
  14. */
  15. private String[] recipientMailbox;
  16. /**
  17. * 抄送人邮箱
  18. */
  19. private String[] ccMailbox;
  20. /**
  21. * 加密抄送人邮箱
  22. */
  23. private String[] bccMailbox;
  24. /**
  25. * 发送内容
  26. */
  27. private String sendContent;
  28. /**
  29. * 真实名称/附件路径
  30. */
  31. private Map<String, String> enclosures;
  32. // 附件是否添加的到正文,默认false不添加
  33. // private Boolean is_;
  34. public String getSubject() {
  35. return subject;
  36. }
  37. public void setSubject(String subject) {
  38. this.subject = subject;
  39. }
  40. public String[] getRecipientMailbox() {
  41. return recipientMailbox;
  42. }
  43. public void setRecipientMailbox(String[] recipientMailbox) {
  44. this.recipientMailbox = recipientMailbox;
  45. }
  46. public String[] getCcMailbox() {
  47. return ccMailbox;
  48. }
  49. public void setCcMailbox(String[] ccMailbox) {
  50. this.ccMailbox = ccMailbox;
  51. }
  52. public String[] getBccMailbox() {
  53. return bccMailbox;
  54. }
  55. public void setBccMailbox(String[] bccMailbox) {
  56. this.bccMailbox = bccMailbox;
  57. }
  58. public String getSendContent() {
  59. return sendContent;
  60. }
  61. public void setSendContent(String sendContent) {
  62. this.sendContent = sendContent;
  63. }
  64. public Map<String, String> getEnclosures() {
  65. return enclosures;
  66. }
  67. public void setEnclosures(Map<String, String> enclosures) {
  68. this.enclosures = enclosures;
  69. }
  70. }

注意:收件人,抄送人,加密抄送人,都可以多个。附件的发送附件的位置需要和项目在同一台服务器上。

6、调用该方法

  1. @PostMapping("/sendMail")
  2. public ResultJson sendMail(@RequestBody SendMailModel model) throws MessagingException {
  3. sendMailUtil.sendMail(model);
  4. return ResultJson.SUCCESS();
  5. }

7、使用postMan测试该方法请求的参数

  1. {
  2. "subject": "测试主题",
  3. "recipientMailbox": [
  4. "666666@qq.com",
  5. "test@test.cn"
  6. ],
  7. "ccMailbox": ["6666666@163.com"],
  8. "bccMailbox": [],
  9. "sendContent": "测试邮件测试人test",
  10. "enclosures": {
  11. "dog2.jpg": "E:\\123\\img\\dog2.png"
  12. }
  13. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/95367
推荐阅读
相关标签
  

闽ICP备14008679号