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 框架提供的,用于開(kāi)啟基于注解方式的定時(shí)任務(wù)支持,該注解主要用在項(xiàng)目啟動(dòng)類(lèi)上。
2.@Scheduled
@Scheduled 注解同樣是 Spring 框架提供的,配置定時(shí)任務(wù)的執(zhí)行規(guī)則,該注解主要用在定時(shí)業(yè)務(wù)方法上。@Scheduled 注解提供有多個(gè)屬性,精細(xì)化配置定時(shí)任務(wù)執(zhí)行規(guī)則
| 屬性 | 說(shuō)明 |
| cron | 類(lèi)似于 cron 的表達(dá)式,可以定制定時(shí)任務(wù)觸發(fā)的秒、分鐘、小時(shí)、月中的日、月、周中的日 |
| zone | 表示在上一次任務(wù)執(zhí)行結(jié)束后在指定時(shí)間后繼續(xù)執(zhí)行下一次任務(wù)(屬性值為long類(lèi)型) |
| fixedDelay | 指定cron 表達(dá)式將被解析的時(shí)區(qū)。默認(rèn)情況下,該屬性是空字符串(即使用服務(wù)器的本地時(shí)區(qū) |
| fixedDelayString | 表示在上一次任務(wù)執(zhí)行結(jié)束后在指定時(shí)間后繼續(xù)執(zhí)行下一次任務(wù)(屬性值為long類(lèi)型的字符串形式) |
| fixedRate | 表示每隔指定時(shí)間執(zhí)行一次任務(wù) (屬性值為 long 類(lèi)型) |
| fixedRateString | 表示每隔指定時(shí)間執(zhí)行一次任務(wù)(屬性值為 long 類(lèi)型的字符串形式) |
| initialDelay | 表示在fixedRate 或fixedDelay 任務(wù)第一次執(zhí)行之前要延遲的毫秒數(shù)(屬性值為long類(lèi)型) |
| initialDelayString | 表示在fixedRate或fixedDelay 任務(wù)第一次執(zhí)行之前要延遲的毫秒數(shù)(屬性值為long類(lèi)型的字符串形式) |
三、前期準(zhǔn)備工作
1、登錄QQ郵箱獲取授權(quán)碼
第一步:進(jìn)入QQ郵箱

第二步:找到POP3/SMTP,并開(kāi)啟

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

2、pom.xml中的依賴(lài)
<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>
<!--添加下面的依賴(lài)后,Spring Boot自動(dòng)配置的郵件服務(wù)會(huì)生效,在郵件發(fā)送任務(wù)時(shí),
可以直接使用Spring框架提供的JavaMailSender接口或者它的實(shí)現(xiàn)類(lèi)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賬戶(hù)和密碼(這里需要大家修改為自己的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ù)處理類(lèi)SendEmailService
注意:在方法上的注解@Async是需要搭配定時(shí)任務(wù)一起使用的,如果使用普通的test類(lèi)時(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)類(lèi)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幫助類(lèi)對(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幫助類(lèi)對(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類(lèi)中發(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)鍵字的固定寫(xiě)法,如果改變將無(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";//注意這里修改為你的硬盤(pán)中有的資源
String filePath="D:\\hahaha.txt";//注意這里修改為你的硬盤(pán)中有的資源
// 發(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>用戶(hù)驗(yàn)證碼</title>
</head>
<body>
<div><span th:text="${username}">XXX</span> 先生/女士,您好:</div>
<P style="text-indent: 2em">您的新用戶(hù)驗(yàn)證碼為<span th:text="$[code]" style="color: cornflowerblue">123456</span>,請(qǐng)妥善保管。</P>
</body>
</html>三、發(fā)送定時(shí)郵件
下面類(lèi)中的 @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)類(lèi)型模板文件然后動(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)鍵字的固定寫(xiě)法,如果改變將無(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";//注意這里修改為你的硬盤(pán)中有的資源
String filePath="D:\\hahaha.txt";//注意這里修改為你的硬盤(pán)中有的資源
// 發(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)類(lèi)上添加基于注解的定時(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)文章
Springboot集成kafka高級(jí)應(yīng)用實(shí)戰(zhàn)分享
這篇文章主要介紹了Springboot集成kafka高級(jí)應(yīng)用實(shí)戰(zhàn)分享,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08
SpringBoot @Scope與@RefreshScope注解使用詳解
spring的bean管理中,每個(gè)bean都有對(duì)應(yīng)的scope。在BeanDefinition中就已經(jīng)指定scope,默認(rèn)的RootBeanDefinition的scope是prototype類(lèi)型,使用@ComponentScan掃描出的BeanDefinition會(huì)指定是singleton,最常使用的也是singleton2022-11-11
Java Http請(qǐng)求傳json數(shù)據(jù)亂碼問(wèn)題的解決
這篇文章主要介紹了Java Http請(qǐng)求傳json數(shù)據(jù)亂碼問(wèn)題的解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
springboot啟動(dòng)腳本start.sh和停止腳本 stop.sh的詳細(xì)教程
這篇文章主要介紹了springboot啟動(dòng)腳本start.sh和停止腳本 stop.sh的詳細(xì)教程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
spring cloud consul使用ip注冊(cè)服務(wù)的方法示例
這篇文章主要介紹了spring cloud consul使用ip注冊(cè)服務(wù)的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
SpringBoot整合Java DL4J實(shí)現(xiàn)文本分類(lèi)系統(tǒng)
在當(dāng)今信息爆炸的時(shí)代,自然語(yǔ)言處理領(lǐng)域中的文本分類(lèi)顯得尤為重要,文本分類(lèi)能夠高效地組織和管理海量的文本數(shù)據(jù),隨著互聯(lián)網(wǎng)的飛速發(fā)展,我們每天都被大量的文本信息所包圍,本文將介紹如何使用 Spring Boot 整合 Java Deeplearning4j 來(lái)構(gòu)建一個(gè)文本分類(lèi)系統(tǒng)2024-10-10
Java try-catch-finally異常處理機(jī)制詳解
這篇文章主要介紹了Java try-catch-finally異常處理機(jī)制詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08

