SpringBoot?Mail郵件任務(wù)詳情
一、引言
發(fā)送郵件應(yīng)該是網(wǎng)站的必備功能之一,什么注冊(cè)驗(yàn)證,忘記密碼或者是給用戶發(fā)送營(yíng)銷信息。最早期的時(shí)候我們會(huì)使用JavaMail相關(guān)api來(lái)寫發(fā)送郵件的相關(guān)代碼,后來(lái)spring退出了JavaMailSender更加簡(jiǎn)化了郵件發(fā)送的過(guò)程,在之后springboot對(duì)此進(jìn)行了封裝就有了現(xiàn)在的spring-boot-starter-mail,本章文章的介紹主要來(lái)自于此包。
二、簡(jiǎn)單使用
1、pom包配置
pom包里面添加spring-boot-starter-mail包引用
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> </dependencies>
2、在application.properties中添加郵箱配置
spring.mail.host=smtp.1234.163.com //郵箱服務(wù)器地址 spring.mail.username=5678@oo.com //用戶名 spring.mail.password=09876 //密碼 spring.mail.default-encoding=UTF-8 mail.fromMail.addr=65432@oo.com //以誰(shuí)來(lái)發(fā)送郵件
3、編寫mailService,這里只提出實(shí)現(xiàn)類。
@Component public class MailServiceImpl implements MailService{ private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private JavaMailSender mailSender; @Value("${mail.fromMail.addr}") private String from; @Override public void sendSimpleMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(content); try { mailSender.send(message); logger.info("簡(jiǎn)單郵件已經(jīng)發(fā)送。"); } catch (Exception e) { logger.error("發(fā)送簡(jiǎn)單郵件時(shí)發(fā)生異常!", e); } } }
4、編寫test類進(jìn)行測(cè)試
@RunWith(SpringRunner.class) @SpringBootTest public class MailServiceTest { @Autowired private MailService MailService; @Test public void testSimpleMail() throws Exception { MailService.sendSimpleMail("123456w@126.com","test simple mail"," hello this is simple mail"); } }
至此一個(gè)簡(jiǎn)單的文本發(fā)送就完成了。
三、加點(diǎn)料
但是在正常使用的過(guò)程中,我們通常在郵件中加入圖片或者附件來(lái)豐富郵件的內(nèi)容,下面講介紹如何使用springboot來(lái)發(fā)送豐富的郵件。
3、發(fā)送html格式郵件
其它都不變?cè)贛ailService添加sendHtmlMail方法.
public void sendHtmlMail(String to, String subject, String content) { MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要?jiǎng)?chuàng)建一個(gè)multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); mailSender.send(message); logger.info("html郵件發(fā)送成功"); } catch (MessagingException e) { logger.error("發(fā)送html郵件時(shí)發(fā)生異常!", e); } }
在測(cè)試類中構(gòu)建html內(nèi)容,測(cè)試發(fā)送:
@Test public void testHtmlMail() throws Exception { String content="<html>\n" + "<body>\n" + " <h3>hello world ! 這是一封Html郵件!</h3>\n" + "</body>\n" + "</html>"; MailService.sendHtmlMail("ityouknow@126.com","test simple mail",content); }
3、發(fā)送帶附件的郵件
在MailService添加sendAttachmentsMail方法.
public void sendAttachmentsMail(String to, String subject, String content, String filePath){ MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); mailSender.send(message); logger.info("帶附件的郵件已經(jīng)發(fā)送。"); } catch (MessagingException e) { logger.error("發(fā)送帶附件的郵件時(shí)發(fā)生異常!", e); } }
添加多個(gè)附件可以使用多條 helper.addAttachment(fileName, file)
4、在測(cè)試類中添加測(cè)試方法
@Test public void sendAttachmentsMail() { String filePath="e:\\tmp\\application.log"; mailService.sendAttachmentsMail("ityouknow@126.com", "主題:帶附件的郵件", "有附件,請(qǐng)查收!", filePath); }
5、發(fā)送帶靜態(tài)資源的郵件
郵件中的靜態(tài)資源一般就是指圖片,在MailService添加sendAttachmentsMail方法.
public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){ MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); mailSender.send(message); logger.info("嵌入靜態(tài)資源的郵件已經(jīng)發(fā)送。"); } catch (MessagingException e) { logger.error("發(fā)送嵌入靜態(tài)資源的郵件時(shí)發(fā)生異常!", e); } }
在測(cè)試類中添加測(cè)試方法:
@Test public void sendInlineResourceMail() { String rscId = "12345"; String content="<html><body>這是有圖片的郵件:<img src=\'cid:" + rscId + "\' ></body></html>"; String imgPath = "C:\\Users\\summer\\Pictures\\favicon.png"; mailService.sendInlineResourceMail("ityouknow@126.com", "主題:這是有圖片的郵件", content, imgPath, rscId); }
添加多個(gè)圖片可以使用多條 <img src='cid:" + rscId + "' > 和 helper.addInline(rscId, res) 來(lái)實(shí)現(xiàn)
到此所有的郵件發(fā)送服務(wù)已經(jīng)完成了。
郵件系統(tǒng):
上面發(fā)送郵件的基礎(chǔ)服務(wù)就這些了,但是如果我們要做成一個(gè)郵件系統(tǒng)的話還需要考慮以下幾個(gè)問(wèn)題:
郵件模板:
我們會(huì)經(jīng)常收到這樣的郵件:
尊敬的neo用戶:
恭喜您注冊(cè)成為xxx網(wǎng)的用戶,,同時(shí)感謝您對(duì)xxx的關(guān)注與支持并歡迎您使用xx的產(chǎn)品與服務(wù)。
...
其中只有neo這個(gè)用戶名在變化,其它郵件內(nèi)容均不變,如果每次發(fā)送郵件都需要手動(dòng)拼接的話會(huì)不夠優(yōu)雅,并且每次模板的修改都需要改動(dòng)代碼的話也很不方便,因此對(duì)于這類郵件需求,都建議做成郵件模板來(lái)處理。模板的本質(zhì)很簡(jiǎn)單,就是在模板中替換變化的參數(shù),轉(zhuǎn)換為html字符串即可,這里以thymeleaf為例來(lái)演示。
四、pom中導(dǎo)入thymeleaf的包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
五、在resorces/templates下創(chuàng)建emailTemplate.html
<!DOCTYPE html> <html lang="zh" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> 您好,這是驗(yàn)證郵件,請(qǐng)點(diǎn)擊下面的鏈接完成驗(yàn)證, <a href="#" rel="external nofollow" th:href="@{ http://www.i123456w.com/neo/{id}(id=${id}) }" rel="external nofollow" >激活賬號(hào)</a> </body> </html>
六、解析模板并發(fā)送
@Test public void sendTemplateMail() { //創(chuàng)建郵件正文 Context context = new Context(); context.setVariable("id", "006"); String emailContent = templateEngine.process("emailTemplate", context); mailService.sendHtmlMail("ityouknow@126.com","主題:這是模板郵件",emailContent); }
1、發(fā)送失敗
因?yàn)楦鞣N原因,總會(huì)有郵件發(fā)送失敗的情況,比如:郵件發(fā)送過(guò)于頻繁、網(wǎng)絡(luò)異常等。在出現(xiàn)這種情況的時(shí)候,我們一般會(huì)考慮重新重試發(fā)送郵件,會(huì)分為以下幾個(gè)步驟來(lái)實(shí)現(xiàn):
- 1、接收到發(fā)送郵件請(qǐng)求,首先記錄請(qǐng)求并且入庫(kù)。
- 2、調(diào)用郵件發(fā)送接口發(fā)送郵件,并且將發(fā)送結(jié)果記錄入庫(kù)。
- 3、啟動(dòng)定時(shí)系統(tǒng)掃描時(shí)間段內(nèi),未發(fā)送成功并且重試次數(shù)小于3次的郵件,進(jìn)行再次發(fā)送
七、異步發(fā)送
很多時(shí)候郵件發(fā)送并不是我們主業(yè)務(wù)必須關(guān)注的結(jié)果,比如通知類、提醒類的業(yè)務(wù)可以允許延時(shí)或者失敗。這個(gè)時(shí)候可以采用異步的方式來(lái)發(fā)送郵件,加快主交易執(zhí)行速度,在實(shí)際項(xiàng)目中可以采用MQ發(fā)送郵件相關(guān)參數(shù),監(jiān)聽(tīng)到消息隊(duì)列之后啟動(dòng)發(fā)送郵件。
到此這篇關(guān)于SpringBoot Mail郵件任務(wù)詳情的文章就介紹到這了,更多相關(guān)SpringBoot Mail 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 使用SpringBoot發(fā)送郵件的方法詳解
- SpringBoot整合郵件發(fā)送的四種方法
- SpringBoot實(shí)現(xiàn)定時(shí)發(fā)送郵件的三種方法案例詳解
- Springboot發(fā)送郵件功能的實(shí)現(xiàn)詳解
- SpringBoot實(shí)現(xiàn)發(fā)送QQ郵件的示例代碼
- 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)文章
SpringCloud Gateway網(wǎng)關(guān)功能介紹與使用
SpringCloud Gateway 是 Spring Cloud 的一個(gè)全新項(xiàng)目,它旨在為微服務(wù)架構(gòu)提供一種簡(jiǎn)單有效的統(tǒng)一的 API 路由管理方式。這篇文章主要介紹了SpringCloud Gateway網(wǎng)關(guān)作用,需要的朋友可以參考下2022-12-12SpringBoot2.3.0配置JPA的實(shí)現(xiàn)示例
這篇文章主要介紹了SpringBoot2.3.0配置JPA的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08Docker環(huán)境下Spring Boot應(yīng)用內(nèi)存飆升分析與解決場(chǎng)景分析
當(dāng)運(yùn)行一個(gè)Spring Boot項(xiàng)目時(shí),如果未設(shè)置JVM內(nèi)存參數(shù),Spring Boot默認(rèn)會(huì)采用JVM自身默認(rèn)的配置策略,接下來(lái)通過(guò)本文給大家介紹Docker環(huán)境下Spring Boot應(yīng)用內(nèi)存飆升分析與解決方法,需要的朋友參考下吧2021-08-08Java調(diào)用opencv實(shí)現(xiàn)圖片矯正功能
這篇文章主要為大家詳細(xì)介紹了Java如何調(diào)用opencv實(shí)現(xiàn)圖片矯正功能,文中的示例代碼簡(jiǎn)潔易懂,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-09-09java 中設(shè)計(jì)模式(值對(duì)象)的實(shí)例詳解
這篇文章主要介紹了java 中設(shè)計(jì)模式(值對(duì)象)的實(shí)例詳解的相關(guān)資料,希望通過(guò)本文能幫助到大家,需要的朋友可以參考下2017-09-09