歡迎閱讀 Spring Boot 2 實戰系列 電子郵件雖然近幾年有點「退火」,可是在開發中依然有舉足輕重的地位。在比較正式的場合咱們依然經過電子郵件來傳遞信息和回執。今天咱們就來學一下如何在 Spring Boot 下發送電子郵件。html
Java 發送郵件依賴 jakarta
項目(原 javaEE)提供的 jakarta.mail
組件, Maven 座標:前端
<dependency> <groupId>com.sun.mail</groupId> <artifactId>jakarta.mail</artifactId> <version>1.6.4</version> <scope>compile</scope> </dependency>
Spring 官方 又將其進行進一步封裝成開箱即用的 spring-boot-starter-mail
項目:java
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
在 Spring Boot 項目中咱們引入上面的 spring-boot-starter-mail
依賴便可爲你的項目集成郵件功能。接下來咱們來對郵件功能進行參數配置。spring
spring-boot-starter-mail
的配置由 MailProperties
配置類提供。在 application.yml
配置文件中以 spring.mail
爲前綴。咱們來看看都有哪些配置項。segmentfault
# 字符集編碼 默認 UTF-8 spring.mail.default-encoding=UTF-8 # SMTP 服務器 host qq郵箱的爲 smtp.qq.com 端口 465 587 spring.mail.host=smtp.qq.com # SMTP 服務器端口 不一樣的服務商不同 spring.mail.port=465 # SMTP 服務器使用的協議 spring.mail.protocol=smtp # SMTP服務器須要身份驗證 因此 要配置用戶密碼 # 發送端的用戶郵箱名 spring.mail.username=business@felord.cn # 發送端的密碼 注意保密 spring.mail.password=oooooxxxxxxxx # 指定mail會話的jndi名稱 優先級較高 通常咱們不使用該方式 spring.mail.jndi-name= # 這個比較重要 針對不一樣的SMTP服務器 都有本身的一些特點配置該屬性 提供了這些配置的 key value 封裝方案 例如 Gmail SMTP 服務器超時配置 spring.mail.properties.mail.smtp.timeout= 5000 spring.mail.properties.<key> = # 指定是否在啓動時測試郵件服務器鏈接,默認爲false spring.mail.test-connection=false
針對不一樣的郵箱有不一樣的配置,因此咱們介紹幾種咱們經常使用的郵箱配置,能夠直接拿來配置。安全
可是請注意不少郵箱須要手動開啓 SMTP 功能,請務必確保該功能打開。若是在公有云上部署請避免使用 25
端口。
# 須要開啓 smtp spring.mail.host=smtp.qq.com spring.mail.port=465 # 發件人的郵箱 spring.mail.username=master@felord.cn # qq 郵箱的第三方受權碼 並不是我的密碼 spring.mail.password=qztgbzfftdwdbjcddff #開啓ssl 不然 503 錯誤 spring.mail.properties.mail.smtp.ssl.enable=true
獲取受權碼的方式參見下圖點擊生成受權碼:服務器
# 須要在設置中開啓 smtp spring.mail.host=smtp.163.com spring.mail.port=465 # 發件人的郵箱 spring.mail.username=youraccount@163.com # 郵箱的受權碼 並不是我的密碼 spring.mail.password=qztgbzfftdwdbjcddff spring.mail.properties.mail.smtp.ssl.enable=true spring.mail.properties.mail.imap.ssl.socketFactory.fallback=false spring.mail.properties.mail.smtp.ssl.socketFactory.class=javax.net.ssl.SSLSocketFactory spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.host=smtp.gmail.com spring.mail.port=587 spring.mail.username=youraccount@gmail.com # 安全建議使用應用程序密碼代替Gmail密碼。參見相關文檔 spring.mail.password=yourpassword # 個性配置 spring.mail.properties.mail.debug=true spring.mail.properties.mail.transport.protocol=smtp spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.connectiontimeout=5000 spring.mail.properties.mail.smtp.timeout=5000 spring.mail.properties.mail.smtp.writetimeout=5000 # TLS , port 587 spring.mail.properties.mail.smtp.starttls.enable=true # SSL, post 465 #spring.mail.properties.mail.smtp.socketFactory.port = 465 #spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.host=smtp-mail.outlook.com spring.mail.port=587 spring.mail.username=youraccount@outlook.com spring.mail.password=yourpassword spring.mail.properties.mail.protocol=smtp spring.mail.properties.mail.tls=true spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.ssl.trust=smtp-mail.outlook.com
配置完畢後咱們就能夠構建咱們本身的郵件發送服務了。app
最簡單的就是發送純文本郵件了,完整代碼以下:socket
package cn.felord.mail.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Component; import javax.annotation.Resource; /** * The Email service. * * @author felord.cn * @since 2020 /1/14 23:22 */ @Component public class EmailService { @Resource private JavaMailSender javaMailSender; @Value("${spring.mail.username}") private String from; /** * 發送純文本郵件. * * @param to 目標email 地址 * @param subject 郵件主題 * @param text 純文本內容 */ public void sendMail(String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(text); javaMailSender.send(message); } }
有時候咱們須要在郵件中攜帶附件。咱們就須要發送 Mime 信息了,代碼以下:spring-boot
/** * 發送郵件並攜帶附件. * 請注意 from 、 to 郵件服務器是否限制郵件大小 * * @param to 目標email 地址 * @param subject 郵件主題 * @param text 純文本內容 * @param filePath 附件的路徑 固然你能夠改寫傳入文件 */ public void sendMailWithAttachment(String to, String subject, String text, String filePath) throws MessagingException { File attachment = new File(filePath); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text); helper.addAttachment(attachment.getName(),attachment); javaMailSender.send(mimeMessage); }
這裏須要注意的是from
、to
郵件服務器是否限制郵件大小,避免郵件超出限定大小。
如今不少的場景是經過電子郵件發送宣傳營銷的富文本,甚至圖文並茂帶連接。因此這個功能很是實用。能夠經過前端編寫適配郵件的 html
模板。將數據動態化注入模板便可。咱們先來寫一個 html :
<html lang="en"> <head> <meta http-equiv="content-type" content="text/html" charset="UTF-8"> <title></title> </head> <body> <h2>你好,朋友</h2> <div> <p>歡迎關注公衆號:<strong>Felordcn</strong></p> <p>同時也歡迎訪問: <a href="https://felord.cn">felord.cn</a></p> <p><img src="cid:qr" alt=""></p> </div> </body> </html>
上面大體上跟咱們平時的 html
基本一致,區別在於若是有內嵌的圖片元素好比 img
標籤 ,其 src
中須要使用佔位符,規則爲 cid:
後緊接着一個你本身定義的標記。好比 qr
。後面會在代碼中體現這個 qr
。
若是使用佔位符則必須指定 <meta http-equiv="content-type" content="text/html" charset="UTF-8">
不然圖片沒法顯示! 固然你也能夠直接把圖片的 url
連接寫入模板,就像下面:
<html lang="en"> <body> <h2>你好,朋友</h2> <div> <p>歡迎關注公衆號:<strong>Felordcn</strong></p> <p>同時也歡迎訪問: <a href="https://felord.cn">felord.cn</a></p> <p><img src="https://ae01.alicdn.com/kf/H29f220acefaa49469b5507ef296085abk.png" alt=""></p> </div> </body> </html>
而後咱們編寫 Java 代碼,實際邏輯是 4.2 章節 的增強,以下:
/** * 發送富文本郵件. * * @param to 目標email 地址 * @param subject 郵件主題 * @param text 純文本內容 * @param filePath 附件的路徑 固然你能夠改寫傳入文件 */ public void sendRichMail(String to, String subject, String text, String filePath) throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text,true); // 圖片佔位寫法 若是圖片連接寫入模板 註釋下面這一行 helper.addInline("qr",new FileSystemResource(filePath)); javaMailSender.send(mimeMessage); }
若是你採用相似上面第二個 HTML 模板,圖片邏輯就不須要了,註釋掉
helper.addInline()
方法便可。
今天咱們對 Spring Boot 發送郵件進行了細緻的概括,對經常使用的郵箱配置進行了列舉。同時對發送各類類型的郵件也進行了實現以及細節上的探討。實際開發中尤爲要注意端口問題和附件大小問題。但願能對你有所幫助。多多關注,更多幹貨盡在 felord.cn。
關注公衆號:Felordcn 獲取更多資訊