Spring Boot 發送郵件全解析

1.前言

歡迎閱讀 Spring Boot 2 實戰系列 電子郵件雖然近幾年有點「退火」,可是在開發中依然有舉足輕重的地位。在比較正式的場合咱們依然經過電子郵件來傳遞信息和回執。今天咱們就來學一下如何在 Spring Boot 下發送電子郵件。html

2. 依賴

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

3. 郵箱配置

spring-boot-starter-mail 的配置由 MailProperties 配置類提供。在 application.yml 配置文件中以 spring.mail 爲前綴。咱們來看看都有哪些配置項。安全

#  字符集編碼 默認 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 端口。app

3.1 QQ 郵箱

# 須要開啓 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
複製代碼

獲取受權碼的方式參見下圖點擊生成受權碼:socket

3.2 163 信箱

# 須要在設置中開啓 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
複製代碼

3.3 gmail

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
複製代碼

3.4 outlook

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
複製代碼

4. 郵件發送服務

配置完畢後咱們就能夠構建咱們本身的郵件發送服務了。spring-boot

4.1 純文本郵件

最簡單的就是發送純文本郵件了,完整代碼以下:post

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);
    }
}
複製代碼

4.2 帶附件的郵件

有時候咱們須要在郵件中攜帶附件。咱們就須要發送 Mime 信息了,代碼以下:

/** * 發送郵件並攜帶附件. * 請注意 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);

    }
複製代碼

這裏須要注意的是 fromto 郵件服務器是否限制郵件大小,避免郵件超出限定大小。

4.3 富文本郵件

如今不少的場景是經過電子郵件發送宣傳營銷的富文本,甚至圖文並茂帶連接。因此這個功能很是實用。能夠經過前端編寫適配郵件的 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() 方法便可。

5. 總結

今天咱們對 Spring Boot 發送郵件進行了細緻的概括,對經常使用的郵箱配置進行了列舉。同時對發送各類類型的郵件也進行了實現以及細節上的探討。實際開發中尤爲要注意端口問題和附件大小問題。但願能對你有所幫助。多多關注,更多幹貨盡在 felord.cn

關注公衆號:Felordcn獲取更多資訊

我的博客:https://felord.cn

相關文章
相關標籤/搜索