Spring Boot 優(yōu)雅地發(fā)送郵件
最近在項(xiàng)目開發(fā)中有向使用者發(fā)送報(bào)警通知的功能,其中報(bào)警媒介就包括郵件,這篇文章就簡單介紹了 Spring Boot 如何快速集成實(shí)現(xiàn)郵件發(fā)送。
通常在實(shí)際項(xiàng)目中,也有其他很多地方會用到郵件發(fā)送,比如通過郵件注冊賬戶/找回密碼,通過郵件發(fā)送訂閱信息等等。
開發(fā)前準(zhǔn)備
下面以 QQ 郵箱為例,其他的郵箱的配置也大同小異。
登錄 QQ 郵箱,點(diǎn)擊設(shè)置->賬戶,開啟IMAP/SMTP服務(wù),并生成授權(quán)碼。
準(zhǔn)備工作做好后,就開始進(jìn)行項(xiàng)目實(shí)戰(zhàn)吧!
Spring Boot 集成郵件發(fā)送
Spring Boot 集成郵件發(fā)送主要分為以下三步:
加入依賴 配置郵件 演示郵件發(fā)送
加入依賴
首先創(chuàng)建一個 Spring Boot 項(xiàng)目,然后在 pom.xml 加入如下依賴(其中 thymeleaf 是為了發(fā)送模版郵件):
????org.springframework.boot
????spring-boot-starter-mail
????org.springframework.boot
????spring-boot-starter-thymeleaf
創(chuàng)建郵件配置
在配置文件 application.properties 中配置郵件的相關(guān)參數(shù),具體內(nèi)容如下:
#?使用?smtp?協(xié)議
spring.mail.protocol?=?smtp
spring.mail.host?=?smtp.qq.com
spring.mail.port?=?587
[email protected]
#?授權(quán)碼
spring.mail.password?=?yourauthorizationcode
spring.mail.test-connection?=?false
spring.mail.properties.mail.smtp.auth?=?false
spring.mail.properties.mail.debug?=?false
spring.mail.properties.mail.mime.splitlongparameters?=?false
spring.mail.default-encoding?=?UTF-8
其中指定了郵件的協(xié)議、端口以及郵件賬戶和授權(quán)碼等。
服務(wù)類
在這里主要介紹發(fā)送簡單郵件、模板等操作,在 service 包下創(chuàng)建 Mailervice 類。
發(fā)送簡單郵件
首先注入 JavaMailSender,然后構(gòu)造 SimpleMailMessage ,調(diào)用 javaMailSender 的 send 方法就可以完成簡單的郵件發(fā)送,具體代碼如下所示:
public?void?sendSimpleMail(String?from,?String?to,?String?subject,?String?text)?{
?SimpleMailMessage?simpleMailMessage?=?new?SimpleMailMessage();
?//?發(fā)件人
?simpleMailMessage.setFrom(from);
?//?收件人
?simpleMailMessage.setTo(to);
?//?郵件主題
?simpleMailMessage.setSubject(subject);
?//?郵件內(nèi)容
?simpleMailMessage.setText(text);
?javaMailSender.send(simpleMailMessage);
}
編寫對應(yīng)的 Controller 層,代碼如下:
@GetMapping("/sendSimpleMail")
public?void?sendSimpleMail()?{
?mailService.sendSimpleMail("[email protected]",
???"[email protected]",
???"歡迎關(guān)注微信公眾號「武培軒」",
???"感謝你這么可愛,這么優(yōu)秀,還來關(guān)注我,關(guān)注了就要一起成長哦~~回復(fù)【資料】領(lǐng)取優(yōu)質(zhì)資源!");
}
調(diào)用發(fā)送簡單郵件接口后,就可以在 QQ 郵箱中收到郵件:

發(fā)送復(fù)雜郵件
雖然簡單的純文本郵件已經(jīng)基本夠用了,但是有的時候,也需要很多樣式來豐富郵件,接下來就來演示下發(fā)送復(fù)雜郵件(文本+圖片+附件)。
首先使用 javaMailSender 創(chuàng)建一個 MimeMessage 實(shí)例,用 MimeMessageHelper 設(shè)置開啟內(nèi)嵌和附件功能,然后通過 addInline 方法嵌入圖片(其中 logo 需要與 text 中的 cid 對應(yīng)起來),addAttachment 方法添加附件,具體代碼如下:
public?ResponseEntity?sendMimeMail(String?from,?String?to,?String?subject,?String?text)?{
?MimeMessage?mimeMessage?=?javaMailSender.createMimeMessage();
?try?{
??MimeMessageHelper?helper?=?new?MimeMessageHelper(mimeMessage,?true);
??helper.setFrom(from);
??helper.setTo(to);
??helper.setSubject(subject);
??//?設(shè)置郵件內(nèi)容,第二個參數(shù)設(shè)置是否支持?text/html?類型
??helper.setText(text,?true);
??helper.addInline("logo",?new?ClassPathResource("img/logo.jpg"));
??helper.addAttachment("logo.pdf",?new?ClassPathResource("doc/logo.pdf"));
??javaMailSender.send(mimeMessage);
??return?ResponseEntity.status(HttpStatus.CREATED).body("發(fā)送成功");
?}?catch?(MessagingException?e)?{
??e.printStackTrace();
??return?ResponseEntity.status(HttpStatus.NOT_FOUND).body("e.getMessage()");
?}
}
編寫對應(yīng)的 Controller 層,代碼如下:
@GetMapping("/sendMimeMail")
public?ResponseEntity?sendMimeMail()?{
?return?mailService.sendMimeMail("[email protected]",
???"[email protected]",
???"歡迎關(guān)注微信公眾號「武培軒」",
???"感謝你這么可愛,這么優(yōu)秀,還來關(guān)注我,關(guān)注了就要一起成長哦~~
"?+
?????"回復(fù)【資料】領(lǐng)取優(yōu)質(zhì)資源!
"?+
?????"發(fā)送模板郵件
Java 的模板引擎有許多,在這里使用的是 Thymeleaf,注入 TemplateEngine,使用它來解析模版,然后將返回的字符串作為內(nèi)容發(fā)送,具體代碼如下:
public?ResponseEntity?sendTemplateMail(String?from,?String?to,?String?subject,?Context?context)?{
?MimeMessage?message?=?javaMailSender.createMimeMessage();
?try?{
??MimeMessageHelper?helper?=?new?MimeMessageHelper(message,?true);
??helper.setFrom(from);
??helper.setTo(to);
??helper.setSubject(subject);
??//?解析郵件模板
??String?text?=?templateEngine.process("mailTemplate",?context);
??helper.setText(template,?true);
??javaMailSender.send(message);
??return?ResponseEntity.status(HttpStatus.CREATED).body("發(fā)送成功");
?}?catch?(Exception?e)?{
??e.printStackTrace();
??return?ResponseEntity.status(HttpStatus.NOT_FOUND).body("e.getMessage()");
?}
}
編寫對應(yīng)的 Controller 層,代碼如下:
@GetMapping("/sendTemplateMail")
public?ResponseEntity?sendTemplateMail()?{
?Context?context?=?new?Context();
?context.setVariable("username",?"武培軒");
?return?mailService.sendTemplateMail("[email protected]",
???"[email protected]",
???"歡迎關(guān)注微信公眾號「武培軒」",
???context);
}
調(diào)用發(fā)送模板郵件接口后,就可以在 QQ 郵箱中收到郵件:

總結(jié)
本文的完整代碼在 https://github.com/wupeixuan/SpringBoot-Learn 的 mail 目錄下。
Spring Boot 集成郵件發(fā)送還是比較簡單的,大家可以下載項(xiàng)目源碼,自己在本地運(yùn)行調(diào)試這個項(xiàng)目,更好地理解如何在 Spring Boot 中開發(fā)郵件服務(wù)。
最好的關(guān)系就是互相成就,大家的點(diǎn)贊、在看、分享、留言就是我創(chuàng)作的最大動力。
參考
https://github.com/wupeixuan/SpringBoot-Learn
完
? ? ? ?
???