前言
眾所周知,現在在后臺服務器中發送郵件已經是一個非常常用的功能了。通常來說雖然html并非是一個非常標準的信息格式,但是至少許多郵件客戶端都至少支持一部分標記語言。 在這邊教程中主要是關于教你如何在spring boot 應用中發送郵件以及使用非常簡單強大的thymeleaf模板引擎來制作郵件內容。
文章末尾附上源碼,已經開源到github上,是我公司做項目的時候處理郵件這一塊用到的。 基本上覆蓋了大部分郵件發送需求。稍微修改了一下,奉獻給有需要的人。當你看完文章在看一下這封源碼,你會對這一塊更加的了解。而且你能掌握常用的郵件發送:
- 純文本郵件
- 內聯圖片郵件
- 帶附件的郵件
純文本郵件
添加依賴(mail starter dependencies)
首先制作并且通過smtp郵件服務器來發送一個純文本郵件。
如果你之前有用過spring boot的話,那你寧該并不好奇在你建立一個新工程的時候,spring boot已經幫你繼承了常用的依賴庫。 通常你只需要在你的 pom.xml 中添加如下依賴即可:
1
2
3
4
|
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-mail</artifactid> </dependency> |
郵件服務器屬性配置(properties configuration)
通常情況下,如果所需要的依賴在 class path 中都是可用的話,這時候spring會自動幫你注冊一個默認實現的郵件發送服務 (default mail sender service)。 spring.mail.host 屬性已經被自動定義了, 所有我們所需要做的事情就是把這個屬性添加到我們應用的 application.properties 配置文件中。
application.properties 在resource文件夾下
spring boot 提供的默認郵件發送服務 其實已經非常強大了,我們可以通過簡單的配置它的屬性就可以了。所謂的屬性其實說白了就是配置它的郵件smtp 服務器:
1
2
3
4
5
|
spring.mail.port= 25 # smtp server port spring.mail.username= # login used for authentication spring.mail.password= # password for the given login spring.mail.protocol=smtp spring.mail.defaultencoding=utf- 8 # default message encoding |
這里附帶一份 gmail 的smtp服務器配置清單:
1
2
3
4
5
6
7
|
spring.mail.host = smtp.gmail.com spring.mail.username = ***** @gmail .com spring.mail.password = **** spring.mail.properties.mail.smtp.auth = true spring.mail.properties.mail.smtp.socketfactory.port = 587 spring.mail.properties.mail.smtp.socketfactory. class = javax.net.ssl.sslsocketfactory spring.mail.properties.mail.smtp.socketfactory.fallback = false |
郵件發送服務(mail sending service)
在這里我們使用 autowired 在注入我們的service, 它主要就是生成郵件的相關信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@service public class mailclient { private javamailsender mailsender; @autowired public mailservice(javamailsender mailsender) { this .mailsender = mailsender; } public void prepareandsend(string recipient, string message) { //todo implement } } |
生成郵件內容
下面是一個簡單的生成郵件內容的代碼。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public void prepareandsend(string recipient, string message) { mimemessagepreparator messagepreparator = mimemessage -> { mimemessagehelper messagehelper = new mimemessagehelper(mimemessage); messagehelper.setto(recipient); messagehelper.setsubject( "sample mail subject" ); messagehelper.settext(message); }; try { mailsender.send(messagepreparator); } catch (mailexception e) { // runtime exception; compiler will not force you to handle it } } |
send() 需要被重寫以接受不同類型的參數變量:
- simplemailmessage: 正如名字所示,這是一個最基本的郵件message的模塊,我們可以給它設置常用的屬性,它并不能夠修改信息的頭,只能發送純文本的文件。
- mimemessage: 通過這個類我們可以構建出比較復雜的郵件內容
- mimemessagepreparator: 這是一個接口類,主要目的是提供一個構建模板方法用來構建 mimemessage 以及當你生成一個實例的時候幫你處理異常信息。官方文檔(也是常識:))建議將mimemessagepreparator作為郵件構建的首選類型。
mimemessagehelper類是mimemessage的裝飾類,它提供了更多的開發人員友好界面,并為類的許多屬性添加了輸入驗證。你可以不用,但是別人肯定會用,而且你會后悔不用 xd。
send() 會拋出 **mailexception ** 異常,這是個運行時異常,也就是通常所說的 runtimeexception。 在消息傳遞失敗的情況下,很可能會重復發送操作,或者至少使用一些更復雜的解決方案處理這種情況,例如:使用相應的堆棧跟蹤記錄錯誤消息。
手動測試
通常如果你想郵件功能,你首先需要擁有一個smtp服務器在你本機的電腦上處理你的請求。 如果你還沒用過,下面給你們推薦一些常用的:
- fakesmtp – a simple server written in java. supported by any operating system with java 1.6 or newer installed.
- – a server with a plain and user friendly interface. for windows only.
- papercut – another simple server designed for windows.
集成測試
你可能或許會感到好奇應該如果寫一個自動化的test來驗證你客戶端的功能。 如果你手動測試的話,你需要開啟smtp 服務器然后在運行你的spring boot客戶端。 在這里給大家推薦一個神器 greenmail, 因為他跟junit單元測試高度集成,可以簡化我們的測試。
添加依賴
greenmail 已經在maven倉庫中了,所以我們唯一所需要做的就是將其依賴加入我們的 pom.xml 配置文件中:
1
2
3
4
5
6
|
<dependency> <groupid>com.icegreen</groupid> <artifactid>greenmail</artifactid> <version> 1.5 . 0 </version> <scope>test</scope> </dependency> |
smtp服務器與test模板
現在呢,說了這么多廢話,我們終于可以創建我們的第一個集成測試類了。 它會啟動spring應用程序并同時運行郵件客戶端。但是在我們編寫實際測試之前呢,我們首先必須要確保smtp服務器正確運行,同時在測試結束的時候能夠正確關閉。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@runwith (springjunit4classrunner. class ) @springapplicationconfiguration (application. class ) public class mailclienttest { private greenmail smtpserver; @before public void setup() throws exception { smtpserver = new greenmail( new serversetup( 25 , null , "smtp" )); smtpserver.start(); } @after public void teardown() throws exception { smtpserver.stop(); } } |
創建郵件客戶端
首先,我們需要注入我們的郵件service在測試類中。之后,我們才能通過grennmail來驗證是否能夠接受到郵件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
@autowired private mailclient mailclient; @test public void shouldsendmail() throws exception { //given string message = "test message content" ; //when mailclient.prepareandsend(recipient, message); //then assertreceivedmessagecontains(message); } private void assertreceivedmessagecontains(string expected) throws ioexception, messagingexception { mimemessage[] receivedmessages = smtpserver.getreceivedmessages(); assertequals( 1 , receivedmessages.length); string content = (string) receivedmessages[ 0 ].getcontent(); asserttrue(content.contains(expected)); } |
發送html郵件
在這里我們主要說一下如何構建html類型的郵件。
thymeleaf 模板引擎
首先在你的 pom.xml 中添加依賴。spring引導將使用其默認設置自動準備引擎
1
2
3
4
|
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-thymeleaf</artifactid> </dependency> |
thymeleaf的默認配置期望所有html文件都放在 **resources/templates ** 目錄下,以.html擴展名結尾。 讓我們創建一個名為mailtemplate.html的簡單文件,我們將使用創建的郵件客戶端類發送:
除了在生成過程中作為參數傳遞的消息的占位符,該模板幾乎不包含任何內容。這不是廢話么-,-
模板處理
創建一個服務類,它主要負責將寫入的模板和外部模型組合在一起,這在我們的例子中是一個簡單的短信。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@service public class mailcontentbuilder { private templateengine templateengine; @autowired public mailcontentbuilder(templateengine templateengine) { this .templateengine = templateengine; } public string build(string message) { context context = new context(); context.setvariable( "message" , message); return templateengine.process( "mailtemplate" , context); } } |
注意:這里的 context。 這里主要使用的 鍵值對 的形式,類似map,將模板里面的需要的變量與值對應起來。 比如: <span th:text="${message}"></span>
, 這里我們通過context就將message的內容賦值給了span。
templateengine類的實例由spring boot thymeleaf自動配置提供。我們所需要做的就是調用process()
方法,該方法接受兩個參數,也就是我們使用的模板的名稱以及充當模型的容器的上下文對象對象。
將新創建的 mailcontentbuilder 注入到mailservice類中。我們需要在prepareandsen() 方法中進行一個小的調整,以利用構建器將生成內容設置為mime消息。我們還使用 settext()
方法的重載變量將 content-type 頭設置為text / html,而不是默認的 text / plain。
測試
需要更新的最后一件事是我們的測試,更確切地說,是接收到的消息的預期內容。只需對驗證邏輯進行一個小的更改,運行測試并檢查結果。
1
2
3
4
5
6
7
8
9
10
11
|
@test public void shouldsendmail() throws exception { //given string message = "test message content" ; //when mailservice.prepareandsend(recipient, message); //then string content = "<span>" + message + "</span>" ; assertreceivedmessagecontains(content); } |
本文到此基本宣告結束。
再次獻上一份我常用的html email模板:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
<!doctype html> <html lang= "en" xmlns= "http://www.w3.org/1999/xhtml" xmlns:th= "http://www.thymeleaf.org" > <head> <meta http-equiv= "content-type" content= "text/html; charset=utf-8" /> <meta name= "viewport" content= "width=device-width, initial-scale=1.0" /> <title>siemens sinnovation</title> <style> .button { background-color: #4caf50; border-radius: 12px; border: none; color: white; padding: 10px 25px; text-align: center; text-decoration: none; display: inline-block; font-size: 18px; margin: 4px 2px; cursor: pointer; box-shadow: 0 8px 16px 0 rgba( 0 , 0 , 0 , 0.2 ), 0 6px 20px 0 rgba( 0 , 0 , 0 , 0.19 ); } .button:hover { box-shadow: 0 12px 16px 0 rgba( 0 , 0 , 0 , 0.24 ), 0 17px 50px 0 rgba( 0 , 0 , 0 , 0.19 ); } </style> </head> <body style= "margin: 0;padding: 0;" > <table align= "center" border= "1" cellpadding= "0" cellspacing= "0" width= "600px" > <tr> <td> <table align= "center" border= "0" cellpadding= "0" cellspacing= "0" width= "600" style= "border-collapse: collapse;" > <tr> <td align= "center" style= "padding: 40px 0 30px 0;" > <!---->  </td> </tr> <tr> <td bgcolor= "#ffffff" style= "padding: 20px 30px 20px 30px" > <h4>the following message was created by <span th:text= "${owner.getname()}" ></span> in the siemens dffa group: </h4> <table border= "0" cellpadding= "0" cellspacing= "0" width= "100%" > <tr> <td><span th:text= "${title}" >title</span></td> </tr> <tr> <td style= "padding: 20px 0 30px 0" > <span th:text= "${description}" >description</span> </td> </tr> <tr> <table border= "0" cellpadding= "0" cellspacing= "0" width= "100%" > <tr> <!--<td align= "center" style= "padding: 5px 0 3px 0" >status:<span--> <!--th:text= "${status}" >status</span></td>--> <!--<td align= "center" style= "padding: 5px 0 3px 0" >date submitted: <span--> <!--th:text= "${createdate}" >createdate</span></td>--> <!--<td align= "center" style= "padding: 5px 0 3px 0" >days left to join:<span--> <!--th:text= "${lefttime}" >lefttime</span></td>--> <td align= "center" style= "padding: 5px 0 3px 0" >status:<span th:text= "${status}" > open for joining</span></td> <td align= "center" style= "padding: 5px 0 3px 0" >date submitted: 28 / 08 / 2017 <span th:text= "${createdate}" >createdate</span></td> <td align= "center" style= "padding: 5px 0 3px 0" >days left to join: 10h<span th:text= "${lefttime}" >lefttime</span></td> </tr> </table> </tr> <tr> <table border= "0" cellpadding= "0" cellspacing= "0" width= "100%" > <tr> <td style= "padding: 40px 0px 10px 0px" > team member: </td> </tr> <tr th:each= "member :${members}" > <td style= "padding: 5px 0px 5px 0px" ><span th:text= "${member.getname()}+', email: '+${member.getemail()}" ></span> </td> </tr> </table> </tr> <tr> <td align= "center" style= "padding: 5px 40px 5px 40px" > <button class = "button" >view details</button> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </body> </html> |
源碼下載:
github 源碼:鏈接地址
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:http://www.jianshu.com/p/13bcaee989fe