SpringBoot實(shí)現(xiàn)發(fā)送郵件功能
背景
有個(gè)小伙伴問(wèn)我你以前發(fā)郵件功能怎么弄的。然后我就給他找了個(gè)demo,正好在此也寫(xiě)一下,分享給大家。
理清痛點(diǎn)
發(fā)送郵件,大家可以想一下,坑的地方在哪?
我覺(jué)得是三個(gè)吧。
第一:郵件白名單問(wèn)題。
第二:郵件超時(shí)問(wèn)題。
第三:郵件帶附件問(wèn)題。
我下面的demo都會(huì)介紹這些問(wèn)題及解決。
實(shí)現(xiàn)方案
準(zhǔn)備工作
我們先要準(zhǔn)備一個(gè)可以發(fā)送的郵箱,我這里以我的163郵箱為例,現(xiàn)在發(fā)送郵件的規(guī)則,要求你輸入一種叫做授權(quán)碼的東西,注意這個(gè)東西不是密碼。
獲取授權(quán)碼的步驟:
當(dāng)選擇開(kāi)啟,通過(guò)驗(yàn)證之后就可以獲取到驗(yàn)證碼。選擇重置驗(yàn)證碼也可以獲取。以前17年的時(shí)候就寫(xiě)過(guò)一個(gè)demo,現(xiàn)在19年又開(kāi)了一個(gè),因?yàn)橐郧暗耐恕?/p>
SpringBoot項(xiàng)目引入郵件包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
yml配置郵件相關(guān)
spring: mail: # 郵件服務(wù)地址 host: smtp.163.com # 端口,可不寫(xiě)默認(rèn) port: 25 # 編碼格式 default-encoding: utf-8 # 用戶(hù)名 username: xxx@163.com # 授權(quán)碼,就是我們剛才準(zhǔn)備工作獲取的代碼 password: xxx # 其它參數(shù) properties: mail: smtp: # 如果是用 SSL 方式,需要配置如下屬性,使用qq郵箱的話需要開(kāi)啟 ssl: enable: true required: true # 郵件接收時(shí)間的限制,單位毫秒 timeout: 10000 # 連接時(shí)間的限制,單位毫秒 connectiontimeout: 10000 # 郵件發(fā)送時(shí)間的限制,單位毫秒 writetimeout: 10000
針對(duì)于上面提的超時(shí)問(wèn)題,捕獲超時(shí)異常就可解決。
郵件發(fā)送工具類(lèi)
主要通過(guò)以下工具類(lèi)就可以滿(mǎn)足發(fā)送java郵件的需要。當(dāng)我們進(jìn)行好 yml 配置后,SpringBoot會(huì)幫助我們自動(dòng)配置 JavaMailSender 我們通過(guò)這個(gè)java類(lèi)就可以實(shí)現(xiàn)操作java來(lái)發(fā)送郵件。以下列舉了幾種常用的郵件。
@Service public class MailService { private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class); @Autowired private JavaMailSender mailSender; private static final String SENDER = "xxx@163.com"; /** * 發(fā)送普通郵件 * * @param to 收件人 * @param subject 主題 * @param content 內(nèi)容 */ @Override public void sendSimpleMailMessge(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(SENDER); message.setTo(to); message.setSubject(subject); message.setText(content); try { mailSender.send(message); } catch (Exception e) { logger.error("發(fā)送簡(jiǎn)單郵件時(shí)發(fā)生異常!", e); } } /** * 發(fā)送 HTML 郵件 * * @param to 收件人 * @param subject 主題 * @param content 內(nèi)容 */ @Override public void sendMimeMessge(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(SENDER); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); mailSender.send(message); } catch (MessagingException e) { logger.error("發(fā)送MimeMessge時(shí)發(fā)生異常!", e); } } /** * 發(fā)送帶附件的郵件 * * @param to 收件人 * @param subject 主題 * @param content 內(nèi)容 * @param filePath 附件路徑 */ @Override public void sendMimeMessge(String to, String subject, String content, String filePath) { MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要?jiǎng)?chuàng)建一個(gè)multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(SENDER); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = file.getFilename(); helper.addAttachment(fileName, file); mailSender.send(message); } catch (MessagingException e) { logger.error("發(fā)送帶附件的MimeMessge時(shí)發(fā)生異常!", e); } } /** * 發(fā)送帶靜態(tài)文件的郵件 * * @param to 收件人 * @param subject 主題 * @param content 內(nèi)容 * @param rscIdMap 需要替換的靜態(tài)文件 */ @Override public void sendMimeMessge(String to, String subject, String content, Map<String, String> rscIdMap) { MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要?jiǎng)?chuàng)建一個(gè)multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(SENDER); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); for (Map.Entry<String, String> entry : rscIdMap.entrySet()) { FileSystemResource file = new FileSystemResource(new File(entry.getValue())); helper.addInline(entry.getKey(), file); } mailSender.send(message); } catch (MessagingException e) { logger.error("發(fā)送帶靜態(tài)文件的MimeMessge時(shí)發(fā)生異常!", e); } } }
發(fā)送郵件的demo
@RunWith(SpringRunner.class) @SpringBootTest public class SpringbooEmailDemoApplicationTests { @Autowired private MailService mailService; private static final String TO = "xxx@qq.com"; private static final String SUBJECT = "測(cè)試郵件"; private static final String CONTENT = "test content"; /** * 測(cè)試發(fā)送普通郵件 */ @Test public void sendSimpleMailMessage() { mailService.sendSimpleMailMessge(TO, SUBJECT, CONTENT); } /** * 測(cè)試發(fā)送html郵件 */ @Test public void sendHtmlMessage() { String htmlStr = "<h1>Test</h1>"; mailService.sendMimeMessge(TO, SUBJECT, htmlStr); } /** * 測(cè)試發(fā)送帶附件的郵件 * @throws FileNotFoundException */ @Test public void sendAttachmentMessage() throws FileNotFoundException { File file = ResourceUtils.getFile("classpath:test.txt"); String filePath = file.getAbsolutePath(); mailService.sendMimeMessge(TO, SUBJECT, CONTENT, filePath); } /** * 測(cè)試發(fā)送帶附件的郵件 * @throws FileNotFoundException */ @Test public void sendPicMessage() throws FileNotFoundException { String htmlStr = "<html><body>測(cè)試:圖片1 <br> <img src=\'cid:pic1\'/> <br>圖片2 <br> <img src=\'cid:pic2\'/></body></html>"; Map<String, String> rscIdMap = new HashMap<>(2); rscIdMap.put("pic1", ResourceUtils.getFile("classpath:pic01.jpg").getAbsolutePath()); rscIdMap.put("pic2", ResourceUtils.getFile("classpath:pic02.jpg").getAbsolutePath()); mailService.sendMimeMessge(TO, SUBJECT, htmlStr, rscIdMap); } }
白名單問(wèn)題
如果是發(fā)送給固定郵箱,可以直接在固定郵箱里面設(shè)置白名單,如果頻繁的發(fā)送給多個(gè)郵箱,最好設(shè)置以下發(fā)送時(shí)間間隔,不要不斷的給某一個(gè)郵箱發(fā)送。
總結(jié)
以上所述是小編給大家介紹的SpringBoot 發(fā)送郵件功能實(shí)現(xiàn),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
相關(guān)文章
使用Spring實(shí)現(xiàn)@Value注入靜態(tài)字段
這篇文章主要介紹了使用Spring實(shí)現(xiàn)@Value注入靜態(tài)字段方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05Java中的CopyOnWriteArrayList你了解嗎
CopyOnWriteArrayList是Java集合框架中的一種線程安全的List實(shí)現(xiàn),這篇文章主要來(lái)和大家聊聊CopyOnWriteArrayList的簡(jiǎn)單使用,需要的可以參考一下2023-06-06java 算法之希爾排序詳解及實(shí)現(xiàn)代碼
這篇文章主要介紹了java 算法之希爾排序詳解及實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-03-03深入了解Java8中的時(shí)區(qū)日期時(shí)間
Java?在?java.time?包中也提供了幾個(gè)類(lèi)用于處理需要關(guān)注時(shí)區(qū)的日期時(shí)間?API,本文將通過(guò)簡(jiǎn)單的示例講講它們的用法,需要的可以參考一下2023-04-04web項(xiàng)目WEB-INF下沒(méi)有web.xml的解決方法
新手如果在web項(xiàng)目創(chuàng)建后WEB-INF下面沒(méi)有出現(xiàn)web.xml,怎么辦?別慌,沒(méi)有web.xml文件的原因是因?yàn)樵趧?chuàng)建web項(xiàng)目的時(shí)候沒(méi)有把創(chuàng)建web.xml勾上。這篇文章主要介紹了web項(xiàng)目WEB-INF下沒(méi)有web.xml的解決方法,需要的朋友可以參考下2022-12-12mybatis plus表的創(chuàng)建時(shí)間和修改時(shí)間的操作方法
這篇文章主要介紹了mybatis plus表的創(chuàng)建時(shí)間和修改時(shí)間的實(shí)現(xiàn)方法,本文給大家分享兩種方法,每種方法通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-09-09