SpringBoot發(fā)送異步郵件流程與實(shí)現(xiàn)詳解
1、基本簡(jiǎn)介
- Servlet階段郵件發(fā)送非常的復(fù)雜,如果現(xiàn)代化的Java開發(fā)是那個(gè)樣子該有多糟糕;現(xiàn)在SpringBoot中集成好了郵件發(fā)送的東西,而且操作十分簡(jiǎn)單容易上手。
- 發(fā)送郵件最主要的一步是需要去對(duì)應(yīng)的郵箱開啟POP3/SMTP 或者 IMAP/SMTP,并且拿到授權(quán)碼!
- 導(dǎo)入依賴包spring-boot-starter-mail。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、郵件發(fā)送流程
首先導(dǎo)入mail的依賴包之后,根據(jù)SpringBoot的自動(dòng)裝配原理。幾乎所有的Bean對(duì)象都給裝配好了,直接拿來可以使用。
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ MimeMessage.class, MimeType.class, MailSender.class })
@ConditionalOnMissingBean(MailSender.class)
@Conditional(MailSenderCondition.class)
@EnableConfigurationProperties(MailProperties.class) //配置文件綁定
@Import({ MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class })
public class MailSenderAutoConfiguration {
static class MailSenderCondition extends AnyNestedCondition {
MailSenderCondition() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
// 配置文件前綴名稱
@ConditionalOnProperty(prefix = "spring.mail", name = "host")
static class HostProperty {
}
@ConditionalOnProperty(prefix = "spring.mail", name = "jndi-name")
static class JndiNameProperty {
}
}
}
簡(jiǎn)單分析一手可以看到只需要配置一下application文件即可,前綴以spring.mail開頭;
spring:
mail:
username: xxxx@163.com
password: 授權(quán)碼
host: smtp.163.com # 不同郵箱對(duì)應(yīng)的服務(wù)器不一樣
default-encoding: UTF-8
# username: xxxx@qq.com
# password: 授權(quán)碼
# host: smtp.qq.com
3、配置線程池
這個(gè)步驟不是必須的,但是使用異步的郵件建議還是配置一下。
@Configuration
@EnableAsync//開啟異步
public class ThreadPoolConfig {
@Bean("threadPool")
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 設(shè)置核心線程數(shù)
executor.setCorePoolSize(5);
// 設(shè)置最大線程數(shù)
executor.setMaxPoolSize(10);
// 設(shè)置隊(duì)列容量
executor.setQueueCapacity(100);
// 設(shè)置線程活躍時(shí)間(秒)
executor.setKeepAliveSeconds(60);
// 設(shè)置默認(rèn)線程名稱
executor.setThreadNamePrefix("Thread-");
// 設(shè)置拒絕策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 等待所有任務(wù)結(jié)束后再關(guān)閉線程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
4、編寫郵件工具類
- 郵件在SpringBoot中被封裝成簡(jiǎn)單純文本郵件、多媒體郵件兩種形式。
- 針對(duì)上述兩種形式的郵件可以進(jìn)行編寫一個(gè)工具類便于操作使用。
public class EmailUtil {
private static final String content = "這是郵件的主內(nèi)容";
// 純文本郵件
public static SimpleMailMessage simple(String from, String to){
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject("歡迎xxx");
message.setText(content);
return message;
}
// 多媒體郵件
public static MimeMessage mimeMessage(MimeMessage message,String from, String to) throws MessagingException {
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject("復(fù)雜郵件主題");
helper.setText("<p style='color: deepskyblue'>這是淺藍(lán)色的文字</p>", true);
helper.addAttachment("1.docx", new File("C:\\Users\\Splay\\Desktop\\說明書.docx"));
helper.addAttachment("1.pdf", new File("C:\\Users\\Splay\\Desktop\\參考.pdf"));
return message;
}
}
5、郵件發(fā)送
郵件發(fā)送是需要時(shí)間的,因此為了不讓用戶等待的時(shí)間過長(zhǎng)建議這里使用異步的形式發(fā)送。避免阻塞
@Service
public class SendEmailService {
// SpringBoot自動(dòng)裝配的郵件發(fā)送實(shí)現(xiàn)類
@Autowired
JavaMailSenderImpl mailSender;
@Async("threadPool")
public void sendSimpleMail(String from, String to) {
SimpleMailMessage message = EmailUtil.simple(from, to);
mailSender.send(message); //簡(jiǎn)單純文本郵件發(fā)送
}
@Async("threadPool")
public void sendMultiPartMail(String from, String to) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessage mimeMessage = EmailUtil.mimeMessage(message,from, to);
mailSender.send(mimeMessage); //復(fù)雜郵件發(fā)送
}
}
6、編寫controller
編寫幾個(gè)controller進(jìn)行測(cè)試
@Controller
public class RouterController {
@Value("${spring.mail.username}")
private String from;
@Autowired
SendEmailService mail;
@RequestMapping("/simple")
@ResponseBody
public String simpleMail(@RequestParam(required = true,name = "mail",defaultValue = "xxx@qq.com") String to) {
mail.sendSimpleMail(from, to);
return "Send SimpleEmail Successful!";
}
@RequestMapping("/complex")
@ResponseBody
public String complexMail(@RequestParam(required = true,name = "mail",defaultValue = "xxx@qq.com") String to) throws MessagingException {
mail.sendMultiPartMail(from, to);
return "Send SimpleEmail Successful!";
}
}
到此這篇關(guān)于SpringBoot發(fā)送異步郵件流程與實(shí)現(xiàn)詳解的文章就介紹到這了,更多相關(guān)SpringBoot發(fā)送異步郵件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入解析java中的靜態(tài)代理與動(dòng)態(tài)代理
本篇文章是對(duì)java中的靜態(tài)代理與動(dòng)態(tài)代理進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過來參考下,希望對(duì)大家有所幫助2013-10-10
Java如何高效實(shí)現(xiàn)Word文檔對(duì)比
在項(xiàng)目協(xié)作、文檔審核或版本迭代的快節(jié)奏工作中,你是否曾為Word文檔的細(xì)微修改而抓狂,下面我們就來一起探討如何利用Java進(jìn)行Word文檔的自動(dòng)化比較吧2025-11-11
Spring Boot集成Redis Stream消息隊(duì)列從入門到實(shí)戰(zhàn)指南
Redis Stream作為Redis 5.0引入的新數(shù)據(jù)類型,提供了完整的消息隊(duì)列功能,成為輕量級(jí)消息中間件的優(yōu)秀選擇,本文給大家介紹Spring Boot集成Redis Stream消息隊(duì)列從入門到實(shí)戰(zhàn)指南,感興趣的朋友跟隨小編一起看看吧2026-03-03
Spring自定義注解實(shí)現(xiàn)數(shù)據(jù)脫敏
在當(dāng)今數(shù)據(jù)安全越來越受到重視的背景下,許多企業(yè)都對(duì)敏感數(shù)據(jù)的保護(hù)有著嚴(yán)格的要求,本文就來深入探討一下如何自定義注解來實(shí)現(xiàn)對(duì)敏感數(shù)據(jù)的脫敏處理吧2024-11-11

