经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
SpringBoot实现定时发送邮件的三种方法案例详解
来源:jb51  时间:2023/3/8 10:59:09  对本文有异议

一、发送邮件的三种方法

1、发送纯文本邮件

2、发送复杂邮件

3、发送模板邮件

二、定时任务介绍

Spring框架的定时任务调度功能支持配置和注解两种方式Spring Boot在Spring框架的基础上实现了继承,并对其中基于注解方式的定时任务实现了非常好的支持。下面,针对 Spring Boot 项目中基于注解方式的定时任务调度的相关注解和使用进行介绍。

1.@EnableScheduling

@EnableScheduling 注解是 Spring 框架提供的,用于开启基于注解方式的定时任务支持,该注解主要用在项目启动类上。

2.@Scheduled

@Scheduled 注解同样是 Spring 框架提供的,配置定时任务的执行规则,该注解主要用在定时业务方法上。@Scheduled 注解提供有多个属性,精细化配置定时任务执行规则

属性说明
cron类似于 cron 的表达式,可以定制定时任务触发的秒、分钟、小时、月中的日、月、周中的日
zone表示在上一次任务执行结束后在指定时间后继续执行下一次任务(属性值为long类型)
fixedDelay指定cron 表达式将被解析的时区。默认情况下,该属性是空字符串(即使用服务器的本地时区
fixedDelayString表示在上一次任务执行结束后在指定时间后继续执行下一次任务(属性值为long类型的字符串形式)
fixedRate表示每隔指定时间执行一次任务 (属性值为 long 类型)
fixedRateString表示每隔指定时间执行一次任务(属性值为 long 类型的字符串形式)
initialDelay表示在fixedRate 或fixedDelay 任务第一次执行之前要延迟的毫秒数(属性值为long类型)
initialDelayString表示在fixedRate或fixedDelay 任务第一次执行之前要延迟的毫秒数(属性值为long类型的字符串形式)

三、前期准备工作

1、登录QQ邮箱获取授权码

第一步:进入QQ邮箱

第二步:找到POP3/SMTP,并开启

第三步:复制授权码

开启过程需要手机号码验证,按照步骤操作即可。开启成功之后,即可获取一个授权码,将该号码保存好,一会使用

2、pom.xml中的依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-web</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.projectlombok</groupId>
  12. <artifactId>lombok</artifactId>
  13. <optional>true</optional>
  14. </dependency>
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-test</artifactId>
  18. <scope>test</scope>
  19. </dependency>
  20. <!--添加下面的依赖后,Spring Boot自动配置的邮件服务会生效,在邮件发送任务时,
  21. 可以直接使用Spring框架提供的JavaMailSender接口或者它的实现类JavaMailSenderImpl邮件
  22. 发送-->
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-mail</artifactId>
  26. </dependency>
  27. </dependencies>

3、在全局配置文件application.properties添加邮件服务配置

  1. # 发件人邮件服务器相关配置
  2. spring.mail.host=smtp.qq.com
  3. spring.mail.port=587
  4. # 配置个人QQ账户和密码(这里需要大家修改为自己的QQ账号和密码,密码是加密后的授权码,授权码的获得后继讲解)
  5. spring.mail.username=QQ@qq.com
  6. spring.mail.password=填入刚刚复制的授权码
  7. spring.mail.default-encoding=UTF-8
  8. # 邮件服务超时时间配置
  9. spring.mail.properties.mail.smtp.connectiontimeout=5000
  10. spring.mail.properties.mail.smtp.timeout=3000
  11. spring.mail.properties.mail.smtp.writetimeout=5000

四、操作

一、创建邮件发送任务管理的业务处理类SendEmailService

注意:在方法上的注解@Async是需要搭配定时任务一起使用的,如果使用普通的test类时可以不用这个注解的

  1. package com.lyn.service;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.core.io.FileSystemResource;
  5. import org.springframework.mail.MailException;
  6. import org.springframework.mail.SimpleMailMessage;
  7. import org.springframework.mail.javamail.JavaMailSenderImpl;
  8. import org.springframework.mail.javamail.MimeMessageHelper;
  9. import org.springframework.scheduling.annotation.Async;
  10. import org.springframework.stereotype.Service;
  11. import javax.mail.MessagingException;
  12. import javax.mail.internet.MimeMessage;
  13. import java.io.File;
  14. /**
  15. * @author:Lyn.R
  16. * @date:2023-02-21 14:54:36
  17. * @Description:
  18. * @note:
  19. **/
  20. @Service
  21. public class SendEmailService {
  22. @Autowired
  23. private JavaMailSenderImpl mailSender;//使用Spring框架提供的实现类JavaMailSenderImpl来实现邮件发送。
  24. @Value("${spring.mail.username}")//借助@Value注解读取全局变量中的spring.mail.username的值来作发件人
  25. private String from;
  26. /**
  27. * 第一种方法:发送纯文本邮件
  28. * @param to 收件人地址
  29. * @param subject 邮件标题
  30. * @param text 邮件内容
  31. */
  32. @Async
  33. public void sendSimpleEmail(String to, String subject, String text) {
  34. // 定制纯文本邮件信息SimpleMailMessage
  35. SimpleMailMessage message = new SimpleMailMessage();
  36. message.setFrom(from);//设置发件人
  37. message.setTo(to);//设置收件人
  38. message.setSubject(subject);//设置邮件标题
  39. message.setText(text);//设置 正文件内容
  40. try {
  41. // 发送邮件
  42. mailSender.send(message);
  43. System.out.println("纯文本邮件发送成功");
  44. } catch (MailException e) {
  45. System.out.println("纯文本邮件发送失败 " + e.getMessage());
  46. e.printStackTrace();
  47. }
  48. }
  49. /**
  50. * 第二种方法:发送复杂邮件(包括静态资源和附件)
  51. * @param to 收件人地址
  52. * @param subject 邮件标题
  53. * @param text 邮件内容
  54. * @param filePath 附件地址
  55. * @param rscId 静态资源唯一标识
  56. * @param rscPath 静态资源地址
  57. */
  58. //sendComplexEmail()方法需要接收的参数除了基本的发送信息外,还包括静态资源唯一标识、静态资源路径和附件路径
  59. @Async
  60. public void sendComplexEmail(String to,String subject,String text,String filePath,String rscId,String rscPath){
  61. // 定制复杂邮件信息MimeMessage
  62. MimeMessage message = mailSender.createMimeMessage();
  63. try {
  64. // 使用MimeMessageHelper帮助类对邮件信息封装处理 ,并设置multipart多部件使用为true
  65. MimeMessageHelper helper = new MimeMessageHelper(message, true);
  66. helper.setFrom(from);
  67. helper.setTo(to);
  68. helper.setSubject(subject);
  69. helper.setText(text, true);
  70. // 设置邮件静态资源
  71. FileSystemResource res = new FileSystemResource(new File(rscPath));
  72. helper.addInline(rscId, res);//设置邮件静态资源的方法
  73. // 设置邮件附件
  74. FileSystemResource file = new FileSystemResource(new File(filePath));
  75. String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
  76. helper.addAttachment(fileName, file);//设置邮件附件的方法
  77. // 发送邮件
  78. mailSender.send(message);
  79. System.out.println("复杂邮件发送成功");
  80. } catch (MessagingException e) {
  81. System.out.println("复杂邮件发送失败 "+e.getMessage());
  82. e.printStackTrace();
  83. } catch (Exception e) {
  84. e.printStackTrace();
  85. }
  86. }
  87. /**
  88. * 第三钟方法:发送模板邮件
  89. * @param to 收件人地址
  90. * @param subject 邮件标题
  91. * @param content 邮件内容
  92. */
  93. @Async
  94. public void sendTemplateEmail(String to, String subject, String content) {
  95. MimeMessage message = mailSender.createMimeMessage();
  96. try {
  97. // 使用MimeMessageHelper帮助类对邮件信息进行封装处理,并设置multipart多部件使用为true
  98. MimeMessageHelper helper = new MimeMessageHelper(message, true);
  99. helper.setFrom(from);
  100. helper.setTo(to);
  101. helper.setSubject(subject);
  102. helper.setText(content, true);
  103. // 发送邮件
  104. mailSender.send(message);
  105. System.out.println("模板邮件发送成功");
  106. } catch (MessagingException e) {
  107. System.out.println("模板邮件发送失败 "+e.getMessage());
  108. e.printStackTrace();
  109. }
  110. }
  111. }

二、在test类中发送邮件

  1. package com.lyn;
  2. import com.lyn.service.SendEmailService;
  3. import org.junit.jupiter.api.Test;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.thymeleaf.TemplateEngine;
  7. import org.thymeleaf.context.Context;
  8. @SpringBootTest
  9. class SpringbootHomeworkEmail0221ApplicationTests {
  10. @Autowired
  11. private SendEmailService sendEmailService;
  12. @Test
  13. public void sendSimpleMailTest() {
  14. String to="12345678@qq.com";//这里修改为你能接收到的邮箱
  15. String subject="【纯文本邮件】标题";
  16. String text="嘟嘟嘟.....";
  17. // 发送简单邮件
  18. sendEmailService.sendSimpleEmail(to,subject,text);
  19. }
  20. @Test
  21. public void sendComplexEmailTest() {
  22. //根据前面定义的复杂邮件发送业务定制各种参数
  23. String to="12345678@qq.com";//修改为你自己的邮件方便接收查看
  24. String subject="【复杂邮件】标题";
  25. // 定义邮件内容
  26. StringBuilder text = new StringBuilder();
  27. //对邮件内容使用了HTML标签编辑邮件内容
  28. text.append("<html><head></head>");
  29. text.append("<body><h1>二月二龙抬头!</h1>");
  30. // cid为嵌入静态资源文件关键字的固定写法,如果改变将无法识别;rscId则属于自定义的静态资源唯一标识,一个邮件内容中可能会包括多个静态资源,该属性是为了区别唯一性的。
  31. String rscId = "img001";
  32. text.append("<img src='cid:" +rscId+"'/></body>");
  33. text.append("</html>");
  34. // 指定静态资源文件和附件路径
  35. String rscPath="D:\\1.jpg";//注意这里修改为你的硬盘中有的资源
  36. String filePath="D:\\hahaha.txt";//注意这里修改为你的硬盘中有的资源
  37. // 发送复杂邮件
  38. sendEmailService.sendComplexEmail(to,subject,text.toString(),filePath,rscId,rscPath);
  39. }
  40. @Autowired
  41. private TemplateEngine templateEngine;
  42. @Test
  43. public void sendTemplateEmailTest() {
  44. String to="12345678@qq.com";
  45. String subject="【模板邮件】标题";
  46. // 使用模板邮件定制邮件正文内容
  47. Context context = new Context();//Context注意正确导入“import org.thymeleaf.context.Context;”
  48. context.setVariable("username", "石头");
  49. context.setVariable("code", "456123");
  50. // 使用TemplateEngine设置要处理的模板页面
  51. String emailContent = templateEngine.process("emailTemplate_vercode", context);
  52. // 发送模板邮件
  53. sendEmailService.sendTemplateEmail(to,subject,emailContent);
  54. }
  55. }

模板文件的html(emailTemplate_vercode.html)

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <html lang="zh" xmlns:th="http://www.thymeleaf.org">
  4. <head>
  5. <meta charset="UTF-8"/>
  6. <title>用户验证码</title>
  7. </head>
  8. <body>
  9. <div><span th:text="${username}">XXX</span>&nbsp;先生/女士,您好:</div>
  10. <P style="text-indent: 2em">您的新用户验证码为<span th:text="$[code]" style="color: cornflowerblue">123456</span>,请妥善保管。</P>
  11. </body>
  12. </html>

三、发送定时邮件

下面类中的 @Scheduled(cron = "*/5 * * * * ?")表达式大家可以去下面的网址生成Cron - 在线Cron表达式生成器 (ciding.cc)

  1. package com.lyn.controller;
  2. import com.lyn.service.SendEmailService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.scheduling.annotation.Scheduled;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.stereotype.Service;
  7. import org.thymeleaf.TemplateEngine;
  8. import org.thymeleaf.context.Context;
  9. /**
  10. * @author:Lyn.R
  11. * @date:2023-02-21 19:55:01
  12. * @Description:
  13. * @note:
  14. **/
  15. @Controller
  16. public class MyScheduled {
  17. @Autowired
  18. private SendEmailService sendEmailService;
  19. @Autowired
  20. //模板引擎(Template Engine), 是用来解析对应类型模板文件然后动态生成由数据和静态页面组成的视图文件的一个工具
  21. private TemplateEngine templateEngine;
  22. @Scheduled(cron = "*/5 * * * * ?")
  23. public void sendSimpleMailTest() {
  24. String to="12345678@qq.com";//这里修改为你能接收到的邮箱
  25. String subject="【纯文本邮件】标题";
  26. String text="嘟嘟嘟.....";
  27. // 发送简单邮件
  28. sendEmailService.sendSimpleEmail(to,subject,text);
  29. }
  30. @Scheduled(cron = "1 * * * * ? ")
  31. public void sendComplexEmailTest() {
  32. //根据前面定义的复杂邮件发送业务定制各种参数
  33. String to="12345678@qq.com";//修改为你自己的邮件方便接收查看
  34. String subject="【复杂邮件】标题";
  35. // 定义邮件内容
  36. StringBuilder text = new StringBuilder();
  37. //对邮件内容使用了HTML标签编辑邮件内容
  38. text.append("<html><head></head>");
  39. text.append("<body><h1>二月二龙抬头!</h1>");
  40. // cid为嵌入静态资源文件关键字的固定写法,如果改变将无法识别;rscId则属于自定义的静态资源唯一标识,一个邮件内容中可能会包括多个静态资源,该属性是为了区别唯一性的。
  41. String rscId = "img001";
  42. text.append("<img src='cid:" +rscId+"'/></body>");
  43. text.append("</html>");
  44. // 指定静态资源文件和附件路径
  45. String rscPath="D:\\1.jpg";//注意这里修改为你的硬盘中有的资源
  46. String filePath="D:\\hahaha.txt";//注意这里修改为你的硬盘中有的资源
  47. // 发送复杂邮件
  48. sendEmailService.sendComplexEmail(to,subject,text.toString(),filePath,rscId,rscPath);
  49. }
  50. @Scheduled(cron = "0 * * * * ? ")
  51. public void sendTemplateEmailTest() {
  52. String to="12345678@qq.com";
  53. String subject="【模板邮件】标题";
  54. // 使用模板邮件定制邮件正文内容
  55. Context context = new Context();//Context注意正确导入“import org.thymeleaf.context.Context;”
  56. context.setVariable("username", "石头");
  57. context.setVariable("code", "456123");
  58. // 使用TemplateEngine设置要处理的模板页面
  59. String emailContent = templateEngine.process("emailTemplate_vercode", context);
  60. // 发送模板邮件
  61. sendEmailService.sendTemplateEmail(to,subject,emailContent);
  62. }
  63. }

四、在项目启动类上添加基于注解的定时任务支持:@EnableScheduling

  1. package com.lyn;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.scheduling.annotation.EnableScheduling;
  5. @SpringBootApplication
  6. @EnableScheduling
  7. public class SpringbootHomeworkEmail0221Application {
  8. public static void main(String[] args) {
  9. SpringApplication.run(SpringbootHomeworkEmail0221Application.class, args);
  10. }
  11. }

注意:邮件发多了,可能会导致qq邮箱认为是垃圾邮件,就会出现报错,所以尽量不要进行邮箱轰炸

到此这篇关于SpringBoot三种方法实现定时发送邮件的案例的文章就介绍到这了,更多相关SpringBoot定时发送邮件内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号