SpringBoot實(shí)現(xiàn)定時(shí)發(fā)送郵件的三種方法案例詳解
一、發(fā)送郵件的三種方法
1、發(fā)送純文本郵件
2、發(fā)送復(fù)雜郵件
3、發(fā)送模板郵件
二、定時(shí)任務(wù)介紹
Spring框架的定時(shí)任務(wù)調(diào)度功能支持配置和注解兩種方式Spring Boot在Spring框架的基礎(chǔ)上實(shí)現(xiàn)了繼承,并對(duì)其中基于注解方式的定時(shí)任務(wù)實(shí)現(xiàn)了非常好的支持。下面,針對(duì) Spring Boot 項(xiàng)目中基于注解方式的定時(shí)任務(wù)調(diào)度的相關(guān)注解和使用進(jìn)行介紹。
1.@EnableScheduling
@EnableScheduling 注解是 Spring 框架提供的,用于開啟基于注解方式的定時(shí)任務(wù)支持,該注解主要用在項(xiàng)目啟動(dòng)類上。
2.@Scheduled
@Scheduled 注解同樣是 Spring 框架提供的,配置定時(shí)任務(wù)的執(zhí)行規(guī)則,該注解主要用在定時(shí)業(yè)務(wù)方法上。@Scheduled 注解提供有多個(gè)屬性,精細(xì)化配置定時(shí)任務(wù)執(zhí)行規(guī)則
| 屬性 | 說(shuō)明 |
| cron | 類似于 cron 的表達(dá)式,可以定制定時(shí)任務(wù)觸發(fā)的秒、分鐘、小時(shí)、月中的日、月、周中的日 |
| zone | 表示在上一次任務(wù)執(zhí)行結(jié)束后在指定時(shí)間后繼續(xù)執(zhí)行下一次任務(wù)(屬性值為long類型) |
| fixedDelay | 指定cron 表達(dá)式將被解析的時(shí)區(qū)。默認(rèn)情況下,該屬性是空字符串(即使用服務(wù)器的本地時(shí)區(qū) |
| fixedDelayString | 表示在上一次任務(wù)執(zhí)行結(jié)束后在指定時(shí)間后繼續(xù)執(zhí)行下一次任務(wù)(屬性值為long類型的字符串形式) |
| fixedRate | 表示每隔指定時(shí)間執(zhí)行一次任務(wù) (屬性值為 long 類型) |
| fixedRateString | 表示每隔指定時(shí)間執(zhí)行一次任務(wù)(屬性值為 long 類型的字符串形式) |
| initialDelay | 表示在fixedRate 或fixedDelay 任務(wù)第一次執(zhí)行之前要延遲的毫秒數(shù)(屬性值為long類型) |
| initialDelayString | 表示在fixedRate或fixedDelay 任務(wù)第一次執(zhí)行之前要延遲的毫秒數(shù)(屬性值為long類型的字符串形式) |
三、前期準(zhǔn)備工作
1、登錄QQ郵箱獲取授權(quán)碼
第一步:進(jìn)入QQ郵箱

第二步:找到POP3/SMTP,并開啟

第三步:復(fù)制授權(quán)碼
開啟過(guò)程需要手機(jī)號(hào)碼驗(yàn)證,按照步驟操作即可。開啟成功之后,即可獲取一個(gè)授權(quán)碼,將該號(hào)碼保存好,一會(huì)使用

2、pom.xml中的依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--添加下面的依賴后,Spring Boot自動(dòng)配置的郵件服務(wù)會(huì)生效,在郵件發(fā)送任務(wù)時(shí),
可以直接使用Spring框架提供的JavaMailSender接口或者它的實(shí)現(xiàn)類JavaMailSenderImpl郵件
發(fā)送-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
3、在全局配置文件application.properties添加郵件服務(wù)配置
# 發(fā)件人郵件服務(wù)器相關(guān)配置 spring.mail.host=smtp.qq.com spring.mail.port=587 # 配置個(gè)人QQ賬戶和密碼(這里需要大家修改為自己的QQ賬號(hào)和密碼,密碼是加密后的授權(quán)碼,授權(quán)碼的獲得后繼講解) spring.mail.username=QQ@qq.com spring.mail.password=填入剛剛復(fù)制的授權(quán)碼 spring.mail.default-encoding=UTF-8 # 郵件服務(wù)超時(shí)時(shí)間配置 spring.mail.properties.mail.smtp.connectiontimeout=5000 spring.mail.properties.mail.smtp.timeout=3000 spring.mail.properties.mail.smtp.writetimeout=5000
四、操作
一、創(chuàng)建郵件發(fā)送任務(wù)管理的業(yè)務(wù)處理類SendEmailService
注意:在方法上的注解@Async是需要搭配定時(shí)任務(wù)一起使用的,如果使用普通的test類時(shí)可以不用這個(gè)注解的
package com.lyn.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
* @author:Lyn.R
* @date:2023-02-21 14:54:36
* @Description:
* @note:
**/
@Service
public class SendEmailService {
@Autowired
private JavaMailSenderImpl mailSender;//使用Spring框架提供的實(shí)現(xiàn)類JavaMailSenderImpl來(lái)實(shí)現(xiàn)郵件發(fā)送。
@Value("${spring.mail.username}")//借助@Value注解讀取全局變量中的spring.mail.username的值來(lái)作發(fā)件人
private String from;
/**
* 第一種方法:發(fā)送純文本郵件
* @param to 收件人地址
* @param subject 郵件標(biāo)題
* @param text 郵件內(nèi)容
*/
@Async
public void sendSimpleEmail(String to, String subject, String text) {
// 定制純文本郵件信息SimpleMailMessage
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);//設(shè)置發(fā)件人
message.setTo(to);//設(shè)置收件人
message.setSubject(subject);//設(shè)置郵件標(biāo)題
message.setText(text);//設(shè)置 正文件內(nèi)容
try {
// 發(fā)送郵件
mailSender.send(message);
System.out.println("純文本郵件發(fā)送成功");
} catch (MailException e) {
System.out.println("純文本郵件發(fā)送失敗 " + e.getMessage());
e.printStackTrace();
}
}
/**
* 第二種方法:發(fā)送復(fù)雜郵件(包括靜態(tài)資源和附件)
* @param to 收件人地址
* @param subject 郵件標(biāo)題
* @param text 郵件內(nèi)容
* @param filePath 附件地址
* @param rscId 靜態(tài)資源唯一標(biāo)識(shí)
* @param rscPath 靜態(tài)資源地址
*/
//sendComplexEmail()方法需要接收的參數(shù)除了基本的發(fā)送信息外,還包括靜態(tài)資源唯一標(biāo)識(shí)、靜態(tài)資源路徑和附件路徑
@Async
public void sendComplexEmail(String to,String subject,String text,String filePath,String rscId,String rscPath){
// 定制復(fù)雜郵件信息MimeMessage
MimeMessage message = mailSender.createMimeMessage();
try {
// 使用MimeMessageHelper幫助類對(duì)郵件信息封裝處理 ,并設(shè)置multipart多部件使用為true
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, true);
// 設(shè)置郵件靜態(tài)資源
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);//設(shè)置郵件靜態(tài)資源的方法
// 設(shè)置郵件附件
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);//設(shè)置郵件附件的方法
// 發(fā)送郵件
mailSender.send(message);
System.out.println("復(fù)雜郵件發(fā)送成功");
} catch (MessagingException e) {
System.out.println("復(fù)雜郵件發(fā)送失敗 "+e.getMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 第三鐘方法:發(fā)送模板郵件
* @param to 收件人地址
* @param subject 郵件標(biāo)題
* @param content 郵件內(nèi)容
*/
@Async
public void sendTemplateEmail(String to, String subject, String content) {
MimeMessage message = mailSender.createMimeMessage();
try {
// 使用MimeMessageHelper幫助類對(duì)郵件信息進(jìn)行封裝處理,并設(shè)置multipart多部件使用為true
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
// 發(fā)送郵件
mailSender.send(message);
System.out.println("模板郵件發(fā)送成功");
} catch (MessagingException e) {
System.out.println("模板郵件發(fā)送失敗 "+e.getMessage());
e.printStackTrace();
}
}
}
二、在test類中發(fā)送郵件
package com.lyn;
import com.lyn.service.SendEmailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
@SpringBootTest
class SpringbootHomeworkEmail0221ApplicationTests {
@Autowired
private SendEmailService sendEmailService;
@Test
public void sendSimpleMailTest() {
String to="12345678@qq.com";//這里修改為你能接收到的郵箱
String subject="【純文本郵件】標(biāo)題";
String text="嘟嘟嘟.....";
// 發(fā)送簡(jiǎn)單郵件
sendEmailService.sendSimpleEmail(to,subject,text);
}
@Test
public void sendComplexEmailTest() {
//根據(jù)前面定義的復(fù)雜郵件發(fā)送業(yè)務(wù)定制各種參數(shù)
String to="12345678@qq.com";//修改為你自己的郵件方便接收查看
String subject="【復(fù)雜郵件】標(biāo)題";
// 定義郵件內(nèi)容
StringBuilder text = new StringBuilder();
//對(duì)郵件內(nèi)容使用了HTML標(biāo)簽編輯郵件內(nèi)容
text.append("<html><head></head>");
text.append("<body><h1>二月二龍?zhí)ь^!</h1>");
// cid為嵌入靜態(tài)資源文件關(guān)鍵字的固定寫法,如果改變將無(wú)法識(shí)別;rscId則屬于自定義的靜態(tài)資源唯一標(biāo)識(shí),一個(gè)郵件內(nèi)容中可能會(huì)包括多個(gè)靜態(tài)資源,該屬性是為了區(qū)別唯一性的。
String rscId = "img001";
text.append("<img src='cid:" +rscId+"'/></body>");
text.append("</html>");
// 指定靜態(tài)資源文件和附件路徑
String rscPath="D:\\1.jpg";//注意這里修改為你的硬盤中有的資源
String filePath="D:\\hahaha.txt";//注意這里修改為你的硬盤中有的資源
// 發(fā)送復(fù)雜郵件
sendEmailService.sendComplexEmail(to,subject,text.toString(),filePath,rscId,rscPath);
}
@Autowired
private TemplateEngine templateEngine;
@Test
public void sendTemplateEmailTest() {
String to="12345678@qq.com";
String subject="【模板郵件】標(biāo)題";
// 使用模板郵件定制郵件正文內(nèi)容
Context context = new Context();//Context注意正確導(dǎo)入“import org.thymeleaf.context.Context;”
context.setVariable("username", "石頭");
context.setVariable("code", "456123");
// 使用TemplateEngine設(shè)置要處理的模板頁(yè)面
String emailContent = templateEngine.process("emailTemplate_vercode", context);
// 發(fā)送模板郵件
sendEmailService.sendTemplateEmail(to,subject,emailContent);
}
}
模板文件的html(emailTemplate_vercode.html)
<!DOCTYPE html>
<html lang="en">
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>用戶驗(yàn)證碼</title>
</head>
<body>
<div><span th:text="${username}">XXX</span> 先生/女士,您好:</div>
<P style="text-indent: 2em">您的新用戶驗(yàn)證碼為<span th:text="$[code]" style="color: cornflowerblue">123456</span>,請(qǐng)妥善保管。</P>
</body>
</html>三、發(fā)送定時(shí)郵件
下面類中的 @Scheduled(cron = "*/5 * * * * ?")表達(dá)式大家可以去下面的網(wǎng)址生成Cron - 在線Cron表達(dá)式生成器 (ciding.cc)
package com.lyn.controller;
import com.lyn.service.SendEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
/**
* @author:Lyn.R
* @date:2023-02-21 19:55:01
* @Description:
* @note:
**/
@Controller
public class MyScheduled {
@Autowired
private SendEmailService sendEmailService;
@Autowired
//模板引擎(Template Engine), 是用來(lái)解析對(duì)應(yīng)類型模板文件然后動(dòng)態(tài)生成由數(shù)據(jù)和靜態(tài)頁(yè)面組成的視圖文件的一個(gè)工具
private TemplateEngine templateEngine;
@Scheduled(cron = "*/5 * * * * ?")
public void sendSimpleMailTest() {
String to="12345678@qq.com";//這里修改為你能接收到的郵箱
String subject="【純文本郵件】標(biāo)題";
String text="嘟嘟嘟.....";
// 發(fā)送簡(jiǎn)單郵件
sendEmailService.sendSimpleEmail(to,subject,text);
}
@Scheduled(cron = "1 * * * * ? ")
public void sendComplexEmailTest() {
//根據(jù)前面定義的復(fù)雜郵件發(fā)送業(yè)務(wù)定制各種參數(shù)
String to="12345678@qq.com";//修改為你自己的郵件方便接收查看
String subject="【復(fù)雜郵件】標(biāo)題";
// 定義郵件內(nèi)容
StringBuilder text = new StringBuilder();
//對(duì)郵件內(nèi)容使用了HTML標(biāo)簽編輯郵件內(nèi)容
text.append("<html><head></head>");
text.append("<body><h1>二月二龍?zhí)ь^!</h1>");
// cid為嵌入靜態(tài)資源文件關(guān)鍵字的固定寫法,如果改變將無(wú)法識(shí)別;rscId則屬于自定義的靜態(tài)資源唯一標(biāo)識(shí),一個(gè)郵件內(nèi)容中可能會(huì)包括多個(gè)靜態(tài)資源,該屬性是為了區(qū)別唯一性的。
String rscId = "img001";
text.append("<img src='cid:" +rscId+"'/></body>");
text.append("</html>");
// 指定靜態(tài)資源文件和附件路徑
String rscPath="D:\\1.jpg";//注意這里修改為你的硬盤中有的資源
String filePath="D:\\hahaha.txt";//注意這里修改為你的硬盤中有的資源
// 發(fā)送復(fù)雜郵件
sendEmailService.sendComplexEmail(to,subject,text.toString(),filePath,rscId,rscPath);
}
@Scheduled(cron = "0 * * * * ? ")
public void sendTemplateEmailTest() {
String to="12345678@qq.com";
String subject="【模板郵件】標(biāo)題";
// 使用模板郵件定制郵件正文內(nèi)容
Context context = new Context();//Context注意正確導(dǎo)入“import org.thymeleaf.context.Context;”
context.setVariable("username", "石頭");
context.setVariable("code", "456123");
// 使用TemplateEngine設(shè)置要處理的模板頁(yè)面
String emailContent = templateEngine.process("emailTemplate_vercode", context);
// 發(fā)送模板郵件
sendEmailService.sendTemplateEmail(to,subject,emailContent);
}
}
四、在項(xiàng)目啟動(dòng)類上添加基于注解的定時(shí)任務(wù)支持:@EnableScheduling
package com.lyn;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SpringbootHomeworkEmail0221Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootHomeworkEmail0221Application.class, args);
}
}注意:郵件發(fā)多了,可能會(huì)導(dǎo)致qq郵箱認(rèn)為是垃圾郵件,就會(huì)出現(xiàn)報(bào)錯(cuò),所以盡量不要進(jìn)行郵箱轟炸
到此這篇關(guān)于SpringBoot三種方法實(shí)現(xiàn)定時(shí)發(fā)送郵件的案例的文章就介紹到這了,更多相關(guān)SpringBoot定時(shí)發(fā)送郵件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 使用SpringBoot發(fā)送郵件的方法詳解
- SpringBoot整合郵件發(fā)送的四種方法
- Springboot發(fā)送郵件功能的實(shí)現(xiàn)詳解
- SpringBoot實(shí)現(xiàn)發(fā)送QQ郵件的示例代碼
- SpringBoot?Mail郵件任務(wù)詳情
- SpringBoot?集成短信和郵件的配置示例詳解
- SpringBoot實(shí)現(xiàn)郵件發(fā)送的示例代碼
- SpringBoot實(shí)現(xiàn)發(fā)送郵件、發(fā)送微信公眾號(hào)推送功能
- Spring?Boot整合郵箱發(fā)送郵件實(shí)例
- SpringBoot實(shí)現(xiàn)發(fā)送電子郵件
- SpringBoot整合JavaMail實(shí)現(xiàn)發(fā)郵件的項(xiàng)目實(shí)踐
相關(guān)文章
IntelliJ中高效重構(gòu)的10個(gè)快捷方式詳解
這篇文章主要為大家介紹了IntelliJ中高效重構(gòu)的10個(gè)快捷方式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
spring boot項(xiàng)目沒(méi)有mainClass如何實(shí)現(xiàn)打包運(yùn)行
這篇文章主要介紹了spring boot項(xiàng)目沒(méi)有mainClass如何實(shí)現(xiàn)打包運(yùn)行,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
解決SpringCloud Feign傳對(duì)象參數(shù)調(diào)用失敗的問(wèn)題
這篇文章主要介紹了解決SpringCloud Feign傳對(duì)象參數(shù)調(diào)用失敗的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Springboot-Starter造輪子之自動(dòng)鎖組件lock-starter實(shí)現(xiàn)
這篇文章主要為大家介紹了Springboot-Starter造輪子之自動(dòng)鎖組件lock-starter實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05
SpringBoot+ThreadLocal+AbstractRoutingDataSource實(shí)現(xiàn)動(dòng)態(tài)切換數(shù)據(jù)源
最近在做業(yè)務(wù)需求時(shí),需要從不同的數(shù)據(jù)庫(kù)中獲取數(shù)據(jù)然后寫入到當(dāng)前數(shù)據(jù)庫(kù)中,因此涉及到切換數(shù)據(jù)源問(wèn)題,所以本文采用ThreadLocal+AbstractRoutingDataSource來(lái)模擬實(shí)現(xiàn)dynamic-datasource-spring-boot-starter中線程數(shù)據(jù)源切換,需要的朋友可以參考下2023-08-08
Springmvc調(diào)用存儲(chǔ)過(guò)程,并返回存儲(chǔ)過(guò)程返還的數(shù)據(jù)方式
這篇文章主要介紹了Springmvc調(diào)用存儲(chǔ)過(guò)程,并返回存儲(chǔ)過(guò)程返還的數(shù)據(jù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
Java?超詳細(xì)講解設(shè)計(jì)模式之原型模式講解
原型模式是用于創(chuàng)建重復(fù)的對(duì)象,同時(shí)又能保證性能。這種類型的設(shè)計(jì)模式屬于創(chuàng)建型模式,它提供了一種創(chuàng)建對(duì)象的最佳方式,今天通過(guò)本文給大家介紹下Java?原型設(shè)計(jì)模式,感興趣的朋友一起看看吧2022-03-03
Postman實(shí)現(xiàn)傳List<String>集合
這篇文章主要介紹了Postman實(shí)現(xiàn)傳List<String>集合方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08

