文章首發自我的微信公衆號: 小哈學Java
我的網站: https://www.exception.site/springboot/spring-boots-send-mailhtml
你們好,後續會間斷地奉上一些 Spring Boot 2.x 相關的博文,包括 Spring Boot 2.x 教程和 Spring Boot 2.x 新特性教程相關,如 WebFlux 等。還有自定義 Starter 組件的進階教程,好比:如何封裝一個自定義圖牀 Starter 啓動器(支持上傳到服務器內部,阿里 OSS 和七牛雲等), 僅僅須要配置相關參數,就能夠將圖片上傳功能集成到現有的項目中。java
好吧,這些都是後話。今天主要來說講如何在 Spring Boot 2.x 版本中集成發送郵件功能。git
能夠說,郵件發送在企業級應用中是比較常見的服務了,如運維報警,用戶激活,廣告推廣等場景,均會使用到它。廢話少說,開幹!github
1、添加依賴面試
2、添加郵件相關配置spring
3、關於受權碼springboot
4、開始編碼服務器
5、總結微信
6、GitHub 源碼地址app
在 pom.xml
文件中添加 spring-boot-starter-mail
依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
在 application.properties
配置文件中添加下面內容:
# 發送郵件的服務器,筆者這裏使用的 QQ 郵件 spring.mail.host=smtp.qq.com spring.mail.username=你的郵箱地址 spring.mail.password=受權碼,或郵箱密碼 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true
yml
格式的配置文件,添加以下:
spring: mail: host: smtp.qq.com #發送郵件的服務器,筆者這裏使用的 QQ 郵件 username: 你的郵箱地址 password: 受權碼,或郵箱密碼 properties.mail.smtp.auth: true properties.mail.smtp.starttls.enable: true default-encoding: utf-8
對於上面的配置,您確定對密碼配置那塊還抱有疑問,若是您使用的是 163 郵箱,或者 Gmail 郵箱,直接使用密碼就能夠了,若是您使用的是 QQ 郵箱,則須要先獲取受權碼。
到底什麼事受權碼? :
下圖截自 QQ 郵箱官方文檔:
登陸 QQ 郵箱:
點擊設置:
跳轉頁面後,點擊帳戶,將頁面往下拖動,您會看到:
驗證成功事後,便可獲取受權碼:
先定義一個郵件服務的接口類, MailService.java
:
package site.exception.springbootmail.service; /** * @author 犬小哈(微信號: 小哈學Java) * @site 我的網站: www.exception.site * @date 2019/4/10 * @time 下午4:19 * @discription **/ public interface MailService { /** * 發送簡單文本的郵件 * @param to * @param subject * @param content * @return */ boolean send(String to, String subject, String content); /** * 發送 html 的郵件 * @param to * @param subject * @param html * @return */ boolean sendWithHtml(String to, String subject, String html); /** * 發送帶有圖片的 html 的郵件 * @param to * @param subject * @param html * @param cids * @param filePaths * @return */ boolean sendWithImageHtml(String to, String subject, String html, String[] cids, String[] filePaths); /** * 發送帶有附件的郵件 * @param to * @param subject * @param content * @param filePaths * @return */ boolean sendWithWithEnclosure(String to, String subject, String content, String[] filePaths); }
接口內定義了四個方法:
send()
: 發送簡單文本的郵件;sendWithHtml()
: 發送 html 的郵件;sendWithImageHtml()
: 發送帶有圖片的 html 的郵件;sendWithWithEnclosure
: 發送帶有附件的郵件;完成接口的定義之後,咱們再定義一個具體實現類,MailServiceImpl.java
:
package site.exception.springbootmail.service.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.mail.MailProperties; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import site.exception.springbootmail.service.MailService; import javax.mail.internet.MimeMessage; /** * @author 犬小哈(微信號: 小哈學Java) * @site 我的網站: www.exception.site * @date 2019/4/10 * @time 下午4:19 * @discription **/ @Service public class MailServiceImpl implements MailService { private final static Logger logger = LoggerFactory.getLogger(MailServiceImpl.class); @Autowired private MailProperties mailProperties; @Autowired private JavaMailSender javaMailSender; /** * 發送簡單文本的郵件 * @param to * @param subject * @param content * @return */ @Override public boolean send(String to, String subject, String content) { logger.info("## Ready to send mail ..."); SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); // 郵件發送來源 simpleMailMessage.setFrom(mailProperties.getUsername()); // 郵件發送目標 simpleMailMessage.setTo(to); // 設置標題 simpleMailMessage.setSubject(subject); // 設置內容 simpleMailMessage.setText(content); try { // 發送 javaMailSender.send(simpleMailMessage); logger.info("## Send the mail success ..."); } catch (Exception e) { logger.error("Send mail error: ", e); return false; } return true; } /** * 發送 html 的郵件 * @param to * @param subject * @param html * @return */ @Override public boolean sendWithHtml(String to, String subject, String html) { logger.info("## Ready to send mail ..."); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = null; try { mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); // 郵件發送來源 mimeMessageHelper.setFrom(mailProperties.getUsername()); // 郵件發送目標 mimeMessageHelper.setTo(to); // 設置標題 mimeMessageHelper.setSubject(subject); // 設置內容,並設置內容 html 格式爲 true mimeMessageHelper.setText(html, true); javaMailSender.send(mimeMessage); logger.info("## Send the mail with html success ..."); } catch (Exception e) { e.printStackTrace(); logger.error("Send html mail error: ", e); return false; } return true; } /** * 發送帶有圖片的 html 的郵件 * @param to * @param subject * @param html * @param cids * @param filePaths * @return */ @Override public boolean sendWithImageHtml(String to, String subject, String html, String[] cids, String[] filePaths) { logger.info("## Ready to send mail ..."); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = null; try { mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); // 郵件發送來源 mimeMessageHelper.setFrom(mailProperties.getUsername()); // 郵件發送目標 mimeMessageHelper.setTo(to); // 設置標題 mimeMessageHelper.setSubject(subject); // 設置內容,並設置內容 html 格式爲 true mimeMessageHelper.setText(html, true); // 設置 html 中內聯的圖片 for (int i = 0; i < cids.length; i++) { FileSystemResource file = new FileSystemResource(filePaths[i]); // addInline() 方法 cid 須要 html 中的 cid (Content ID) 對應,才能設置圖片成功, // 具體能夠參見,下面 4.3.3 單元測試的參數設置 mimeMessageHelper.addInline(cids[i], file); } javaMailSender.send(mimeMessage); logger.info("## Send the mail with image success ..."); } catch (Exception e) { e.printStackTrace(); logger.error("Send html mail error: ", e); return false; } return true; } /** * 發送帶有附件的郵件 * @param to * @param subject * @param content * @param filePaths * @return */ @Override public boolean sendWithWithEnclosure(String to, String subject, String content, String[] filePaths) { logger.info("## Ready to send mail ..."); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = null; try { mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); // 郵件發送來源 mimeMessageHelper.setFrom(mailProperties.getUsername()); // 郵件發送目標 mimeMessageHelper.setTo(to); // 設置標題 mimeMessageHelper.setSubject(subject); // 設置內容 mimeMessageHelper.setText(content); // 添加附件 for (int i = 0; i < filePaths.length; i++) { FileSystemResource file = new FileSystemResource(filePaths[i]); String attachementFileName = "附件" + (i + 1); mimeMessageHelper.addAttachment(attachementFileName, file); } javaMailSender.send(mimeMessage); logger.info("## Send the mail with enclosure success ..."); } catch (Exception e) { logger.error("Send html mail error: ", e); return false; } return true; } }
完成上面功能類的編碼後,看下項目結構以下:
填寫相關測試參數,包括目標郵箱地址,標題,內容,運行單元測試:
單元測試經過,再看下實際效果:
郵件正常發送。
填寫相關測試參數,包括目標郵箱地址,標題,html 內容,運行單元測試經過,直接看效果:
能夠看到,郵件發送成功!
填寫相關測試參數,包括目標郵箱地址,標題,html 內容,html 中包含了兩張圖片,而且 src
中的內容是 cid:{flag}
的格式,前綴 cid:
是固定的,您須要改變是後面的標誌位,經過 addInline(cid, file)
來將 cid
和具體的圖片文件對應起來。
運行單元測試經過,看看效果如何:
能夠看到 html 中圖片也是 OK 的。
PS: 這裏筆者在測試發送給 QQ 郵箱的時候,圖片顯示不成功,暫時還沒找到問題在哪,若是有哪位讀者知道,不妨後臺發個消息告訴一下筆者哈。
填寫相關測試參數,包括目標郵箱地址,標題,內容,並添加了兩個附件,運行單元測試,看看實際效果:
發送成功,到此全部的單元測試所有運行經過。
本文中,咱們學習如何在 Spring Boot 2.x 版本中集成發送郵件功能,包括髮送簡單文本,Html 內容,帶有圖片的 Html 內容,以及帶有的附加的郵件,但願對您有所幫助!
https://github.com/weiwosuoai/spring-boot-tutorial/tree/master/spring-boot-mail
最近在網上發現一個不錯的 PDF 資源《Java 核心面試知識.pdf》分享給你們,不光是面試,學習,你都值得擁有!!!
獲取方式: 關注公衆號: 小哈學Java, 後臺回覆 資源,既可獲取資源連接,下面是目錄以及部分截圖:
重要的事情說兩遍,獲取方式: 關注公衆號: 小哈學Java, 後臺回覆 資源,既可獲取資源連接 !!!