Spring boot學習(九)Spring boot配置郵件傳送
前言
郵件傳送這一功能在實際的專案中使用的是非常普遍的,使用者忘記賬戶忘記密碼等很多操作都是通過郵件的方式來互動,因此郵件傳送在 web
開發中是必不可少一個功能模組,本文就主要介紹如何在 spring boot
中傳送不同型別的郵件。
Spring boot中配置步驟
Spring
本身提供了很好用的 org.springframework.mail.javamail.JavaMailSender
介面來實現郵件傳送功能, Spring boot
中也為此提供了自動化配置,所以我們使用起來非常方便。
新增依賴
首先在 pom.xml
檔案中新增如下依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
修改配置檔案
新增依賴之後就需要在專案配置檔案 application.properties
中配置傳送郵件相關的引數,具體如下:
spring.mail.host=smtp.163.com spring.mail.username=xxx spring.mail.password=xxx spring.mail.default-encoding=UTF-8
重要的引數就這些,其它的使用預設的即可,以下為解釋:
-
spring.mail.host
:郵箱伺服器地址,這個根據自己使用什麼郵箱有區別,比如:smtp.163.com smtp.126.com smtp.qq.com
-
spring.mail.username
:郵箱登陸使用者名稱。 -
spring.mail.password
:第三方登陸授權碼(下面會具體介紹該授權碼的獲取方式)。 -
spring.mail.default-encoding
:編碼方式
POP3/SMTP
服務
上面提到了授權碼的概念,首先要明確一個概念就是授權碼跟我們直接登陸郵箱的密碼不是一樣的,授權碼可以理解為第三方客戶端登陸郵箱的密碼,要想獲取授權碼需要我們去自己所用郵箱的官網設定開啟 POP3/SMTP
以及 IMAP/SMTP
服務,我這裡就以自己使用的 163
賬號為例介紹開啟該服務以及獲取授權碼的步驟,如圖:

在這裡插入圖片描述
登陸 163
郵箱官網,按照圖示步驟進行操作,在選擇了服務之後會給你傳送驗證碼,輸入驗證碼之後就會讓你自己設定授權碼,這裡的授權碼就是上邊配置檔案中 spring.mail.password
需要填寫的值。
封裝郵件工具類
對郵件的操作最好是封裝一個類以便程式碼重用以及維護,我這裡封裝成一個 service
層。
定義介面 IMailService.interface
:
package com.web.springbootmail.service; /** * @author Promise * @createTime 2019年3月30日 下午3:14:14 * @description */ public interface IMailService { /** * 簡單文字郵件 * @param toUser 郵件接收者 */ void simpleMil(String toUser)throws Exception; /** * html郵件 * @param toUser 郵件接收者 */ void htmlMail(String toUser) throws Exception; /** * 帶附件郵件 * @param toUser 郵件接收者 */ void attachmentMail(String toUser)throws Exception; /** * 帶圖片郵件 * @param toUser 郵件接收者 */ void imgMail(String toUser)throws Exception; /** * 模板郵件 * @param toUser 郵件接收者 */ void TemplateMail(String toUser)throws Exception; }
實現類 MailServiceimpl.java
:
package com.web.springbootmail.service.impl; import java.io.File; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; 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.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import com.web.springbootmail.service.IMailService; /** * @author Promise * @createTime 2019年3月30日 下午3:14:37 * @description郵件傳送服務類 */ @Service("mailService") public class MailServiceImpl implements IMailService{ @Autowired private JavaMailSender jms; @Autowired private TemplateEngine templateEngine; @Value("${spring.mail.username}") private String from; @Override public void simpleMil(String toUser) { } @Override public void htmlMail(String toUser) { // TODO Auto-generated method stub } @Override public void attachmentMail(String toUser) { // TODO Auto-generated method stub } @Override public void imgMail(String toUser) { // TODO Auto-generated method stub } @Override public void TemplateMail(String toUser) { // TODO Auto-generated method stub } }
這裡只給出了框架,具體實現下面依次介紹,上面還注入了三個變數:
jms templateEngine from
下面介紹每一種郵件的具體實現
簡單文字郵件
這一類郵件最簡單,使用 SimpleMailMessage
物件,程式碼如下:
@Override public void simpleMil(String toUser) { // TODO Auto-generated method stub //初始化簡單郵件物件 SimpleMailMessage message = new SimpleMailMessage(); //郵件傳送者 message.setFrom(from); //郵件接收者 message.setTo(toUser); //郵件標題 message.setSubject("簡單郵件"); //郵件內容 message.setText("簡單內容"); //傳送郵件 jms.send(message); }
html郵件
這一類郵件使用的是 MimeMessage
物件,可豐富頁面樣式,程式碼如下:
@Override public void htmlMail(String toUser) throws MessagingException { // TODO Auto-generated method stub MimeMessage message = jms.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(toUser); helper.setSubject("html格式郵件"); //內容為html格式 String content = "<p style='color:yellow;'>這是一封html格式的檔案</p><h1>這是一封html格式的檔案</h1>"; //true表示以html格式傳送郵件 helper.setText(content, true); jms.send(message); }
帶附件的郵件
這一類郵件多了新增附件的過程,也使用 MimeMessage
,程式碼如下:
@Override public void attachmentMail(String toUser) throws MessagingException { // TODO Auto-generated method stub MimeMessage message = jms.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(toUser); helper.setSubject("帶附件郵件"); //載入絕對路徑資源 FileSystemResource fs = new FileSystemResource(new File("D:\\DownLoad\\file\\阿里巴巴Java開發手冊v1.2.0.pdf")); helper.setText("這是一封帶附件的郵件!"); //新增附件資源 helper.addAttachment("阿里巴巴Java開發手冊v1.2.0.pdf", fs); jms.send(message); }
這裡的檔案路徑本地檔案的絕對路勁。
帶圖片的郵件
程式碼如下:
@Override public void imgMail(String toUser) throws MessagingException { // TODO Auto-generated method stub MimeMessage message = jms.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(toUser); helper.setSubject("帶圖片郵件"); //設定資源的cid String content = "<html><body>部落格頭像<img src='cid:img'/></body></html>"; helper.setText(content, true); FileSystemResource fs = new FileSystemResource(new File("D:\\DownLoad\\img\\20171123181522_c48800.jpg")); //和上邊的cid要對應 helper.addInline("img", fs); jms.send(message); }
其實這種方式也是html郵件,只是多了靜態資源,比如我們這裡就在頁面上添加了一張圖片,步驟跟新增附件有點類似,但是需要注意的是靜態資源需要給靜態資源設定cid,以便存在多個靜態資源區分。
模板郵件
模板郵件指的是郵件的主體內容都是一樣的,只是有一部分不一樣,這樣我們就可以定義一個郵件的模板,傳送郵件的時候我們直接傳入引數就可以了,是一種很好的封裝。
這裡我使用的模板解析框架為 thymeleaf
,所以需要先在專案 pom.xml
檔案中新增依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
接下來在 src/main/resources/templates
目錄下新建 MailTemplate.html
檔案,內容如下:
<!DOCTYPE html> <html lang="zh" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h2>您好,<span th:text="${username}"></span>:這是來自測試的郵件模板!</h2> </body> </html>
使用具體程式碼如下:
@Override public void TemplateMail(String toUser) throws MessagingException { // TODO Auto-generated method stub MimeMessage message = jms.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(toUser); helper.setSubject("模板郵件"); Context context = new Context(); //給模板傳入引數,username要與模板中變數名一致,promise為測試資料 context.setVariable("username", "promise"); //thymeleaf模板預設會從src/main/resources/tempaltes目錄下尋找檔案,填入我們定義的模板名,不需要寫字尾。 String template = templateEngine.process("MailTemplate", context); helper.setText(template, true); jms.send(message); }
controller呼叫
封裝好了傳送郵件的工具類之後,我們直接在 controller
呼叫即可,程式碼如下:
package com.web.springbootmail.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.web.springbootmail.service.IMailService; /** * @author Promise * @createTime 2019年4月1日 下午9:30:38 * @description郵件傳送 */ @RequestMapping("/mail") @RestController public class EmailController { @Autowired private IMailService mailService; @GetMapping("/simple") public Map<String, Object> sendSimpleMail() { Map<String, Object> map =new HashMap<>(); try { //引數就是接收郵件的郵箱,根據自己實際填寫 mailService.simpleMil("*****@qq.com"); map.put("res", "success"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); map.put("res", "error"); } return map; } @GetMapping("/htmlMail") public Map<String, Object> htmlMail(){ Map<String, Object> map =new HashMap<>(); try { mailService.htmlMail("*****@qq.com"); map.put("res", "success"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); map.put("res", "error"); } return map; } @GetMapping("/attachmentsMail") public Map<String, Object> attachmentsMail(){ Map<String, Object> map =new HashMap<>(); try { mailService.attachmentMail("*****@qq.com"); map.put("res", "success"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); map.put("res", "error"); } return map; } @GetMapping("/imgMail") public Map<String, Object> imgMail(){ Map<String, Object> map =new HashMap<>(); try { mailService.imgMail("*****@qq.com"); map.put("res", "success"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); map.put("res", "error"); } return map; } @GetMapping("/templateMail") public Map<String, Object> templateMail(){ Map<String, Object> map =new HashMap<>(); try { mailService.TemplateMail("*****@qq.com"); map.put("res", "success"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); map.put("res", "error"); } return map; } }
效果測試
簡單郵件效果
啟動專案,訪問 localhost:8080/mail/simple
,此時我的收件箱收到如下郵件:

在這裡插入圖片描述
html郵件
訪問 localhost:8080/mail/htmlMail
,效果如下:

在這裡插入圖片描述
帶附件郵件
訪問 localhost:8080/mail/attachmentsMail
,效果如下:

在這裡插入圖片描述
帶圖片郵件
訪問 localhost:8080/mail/imgMail
,效果如下:

在這裡插入圖片描述
模板郵件
訪問 localhost:8080/mail/templateMail
,效果如下:

在這裡插入圖片描述
結語
好了,關於 spring boot
配置郵件傳送功能就到這裡了,感謝閱讀,bye~