Spring Boot 2.0 圖文教程 | 集成郵件發送功能


Spring Boot 2.x 集成郵件發送功能

文章首發自個人微信公眾號: 小哈學Java
個人網站: https://www.exception.site/springboot/spring-boots-send-mail

大家好,后續會間斷地奉上一些 Spring Boot 2.x 相關的博文,包括 Spring Boot 2.x 教程和 Spring Boot 2.x 新特性教程相關,如 WebFlux 等。還有自定義 Starter 組件的進階教程,比如:如何封裝一個自定義圖床 Starter 啟動器(支持上傳到服務器內部,阿里 OSS 和七牛雲等), 僅僅需要配置相關參數,就可以將圖片上傳功能集成到現有的項目中。

好吧,這些都是后話。今天主要來講講如何在 Spring Boot 2.x 版本中集成發送郵件功能。

可以說,郵件發送在企業級應用中是比較常見的服務了,如運維報警,用戶激活,廣告推廣等場景,均會使用到它。廢話少說,開干!

目錄

一、添加依賴

二、添加郵件相關配置

三、關於授權碼

  • 3.1 什么是 QQ 郵箱授權碼
  • 3.2 如何獲取

四、開始編碼

  • 4.1 定義功能類
  • 4.2 項目結構
  • 4.3 單元測試,驗證效果

五、總結

六、GitHub 源碼地址

一、添加依賴

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 郵箱,則需要先獲取授權碼。

到底什么事授權碼? :

3.1 什么是 QQ 郵箱授權碼

下圖截自 QQ 郵箱官方文檔:

什么是授權碼

3.2 如何獲取

登錄 QQ 郵箱:

設置

點擊設置:

賬戶

跳轉頁面后,點擊賬戶,將頁面往下拖動,您會看到:

開啟 smtp 服務

驗證成功過后,即可獲取授權碼:

獲取授權碼

四、開始編碼

4.1 定義功能類

先定義一個郵件服務的接口類, 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);

}

接口內定義了四個方法:

  1. send(): 發送簡單文本的郵件;
  2. sendWithHtml(): 發送 html 的郵件;
  3. sendWithImageHtml(): 發送帶有圖片的 html 的郵件;
  4. 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;
    }
}

4.2 項目結構

完成上面功能類的編碼后,看下項目結構如下:

項目結構

4.3 單元測試,驗證效果

4.3.1 簡單文本發送

簡單文本發送

填寫相關測試參數,包括目標郵箱地址,標題,內容,運行單元測試:

單元測試通過

單元測試通過,再看下實際效果:

簡單文本發送效果

郵件正常發送。

4.3.2 發送 Html

發送 html

填寫相關測試參數,包括目標郵箱地址,標題,html 內容,運行單元測試通過,直接看效果:

發送 html 效果

可以看到,郵件發送成功!

4.3.3 發送帶有圖片的 Html

發送帶圖片的html

填寫相關測試參數,包括目標郵箱地址,標題,html 內容,html 中包含了兩張圖片,並且 src 中的內容是 cid:{flag}的格式,前綴 cid:是固定的,您需要改變是后面的標志位,通過 addInline(cid, file) 來將 cid 和具體的圖片文件對應起來。

運行單元測試通過,看看效果如何:

發送帶圖片的html效果

可以看到 html 中圖片也是 OK 的。

PS: 這里筆者在測試發送給 QQ 郵箱的時候,圖片顯示不成功,暫時還沒找到問題在哪,如果有哪位讀者知道,不妨后台發個消息告訴一下筆者哈。

4.3.4 發送帶有附件的郵件

發送帶有附件的郵件填寫相關測試參數,包括目標郵箱地址,標題,內容,並添加了兩個附件,運行單元測試,看看實際效果:

發送帶有附件的郵件效果

發送成功,到此所有的單元測試全部運行通過。

五、總結

本文中,我們學習如何在 Spring Boot 2.x 版本中集成發送郵件功能,包括發送簡單文本,Html 內容,帶有圖片的 Html 內容,以及帶有的附加的郵件,希望對您有所幫助!

六、GitHub 源碼地址

https://github.com/weiwosuoai/spring-boot-tutorial/tree/master/spring-boot-mail

贈送 | 面試&學習福利資源

最近在網上發現一個不錯的 PDF 資源《Java 核心面試知識.pdf》分享給大家,不光是面試,學習,你都值得擁有!!!

獲取方式: 關注公眾號: 小哈學Java, 后台回復 資源,既可獲取資源鏈接,下面是目錄以及部分截圖:

福利資源截圖

福利資源截圖

福利資源截圖

福利資源截圖

福利資源截圖

福利資源截圖

福利資源截圖

重要的事情說兩遍,獲取方式: 關注公眾號: 小哈學Java, 后台回復 資源,既可獲取資源鏈接 !!!

歡迎關注微信公眾號: 小哈學Java

小哈學Java


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM