SpringBoot加email服務(wù),你說有沒有搞頭?

1. 開啟郵箱POP3/SMTP服務(wù)

登錄qq郵箱后,點(diǎn)擊左上方的設(shè)置,選擇賬戶,如下圖。

然后一直往下滑,看到如下圖的POP3/SMTP服務(wù),點(diǎn)擊開啟,會(huì)讓幫定的密保手機(jī)號(hào)發(fā)個(gè)[短信]到指定號(hào)碼,然后會(huì)收到一個(gè)授權(quán)碼,這個(gè)授權(quán)碼在appliction.properties配置中會(huì)用到,一定要好好保存,開啟后如下圖

2. springboot項(xiàng)目添加依賴

創(chuàng)建springboot項(xiàng)目,添加email依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

我的依賴如下:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.5.3</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.2</version>
    </dependency>

    <!-- 模板引擎,發(fā)送模板郵件用到 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <!--        email-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>

</dependencies>

3. 配置文件

######qq郵箱########
#協(xié)議
spring.mail.protocol=smtp
#郵箱服務(wù)器地址
spring.mail.host=smtp.qq.com
#郵箱服務(wù)器地址
spring.mail.username=xxx@qq.com
#這里的password不是登錄密碼,是開啟POP3之后設(shè)置的客戶端授權(quán)碼
#郵箱密碼,開啟POP3/SMTP服務(wù)時(shí)會(huì)有給你
spring.mail.password=自己POP3/SMTP服務(wù)密碼
#編碼格式
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
##默認(rèn)端口25,使用465端口時(shí),需要添加配置:
spring.mail.port=465
spring.mail.properties.mail.smtp.ssl.enable=true

4. 郵件服務(wù)操作類

springboot引用模塊都通常都提供一個(gè)xxxTmplate,方便我們開發(fā),我們可以封裝一個(gè)EmailTmplate

package com.ljw.task.config;

import lombok.Getter;
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.thymeleaf.TemplateEngine;
import org.thymeleaf.context.IContext;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @Description: 郵件操作類
 * @Author: jianweil
 * @date: 2021/11/19 15:07
 */
@Service
@Getter
public class EmailTemplate {

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private TemplateEngine templateEngine;

    //@Resource
    //private MailProperties mailProperties;

    /**
     * 發(fā)送簡(jiǎn)單文本郵件
     *
     * @param from    發(fā)送者郵箱
     * @param to      接受者郵箱
     * @param subject 郵件主題
     * @param text    郵件內(nèi)容
     */
    public void sendTextMail(String from, String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        // 發(fā)送者
        message.setFrom(from);
        // 接收者
        message.setTo(to);
        //郵件主題
        message.setSubject(subject);
        // 郵件內(nèi)容
        message.setText(text);
        javaMailSender.send(message);
    }

    /**
     * 發(fā)送Html郵件
     *
     * @param from    發(fā)送者郵箱
     * @param to      接受者郵箱
     * @param subject 郵件主題
     * @param html    郵件內(nèi)容 帶html標(biāo)簽
     */
    public void sendHtmlMail(String from, String to, String subject, String html) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(html, true);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("Messaging  Exception !", e);
        }
    }

    /**
     * 發(fā)送附件郵件
     *
     * @param from               發(fā)送者郵箱
     * @param to                 接受者郵箱
     * @param subject            郵件主題
     * @param text               郵件內(nèi)容
     * @param attachmentFilename 附件名稱
     * @param file               附件
     */
    public void sendAttachmentMail(String from, String to, String subject, String text, String attachmentFilename, FileSystemResource file) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text);
            //加入郵件
            helper.addAttachment(attachmentFilename, file);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("Messaging  Exception !", e);
        }
    }

    /**
     * 發(fā)送內(nèi)聯(lián)資源郵件
     *
     * @param from      發(fā)送者郵箱
     * @param to        接受者郵箱
     * @param subject   郵件主題
     * @param text      郵件內(nèi)容,包含內(nèi)聯(lián)文件id 如: String text = "<html><body>宮崎駿電影圖片:<img src='cid:" + contentId + "' ></body></html>";
     * @param contentId 內(nèi)聯(lián)文件id
     * @param file      文件
     */
    public void sendInlineResourceMail(String from, String to, String subject, String text, String contentId, FileSystemResource file) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text, true);
            helper.addInline(contentId, file);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("Messaging  Exception !", e);
        }
    }

    /**
     * 發(fā)送模板郵件
     *
     * @param from     發(fā)送者郵箱
     * @param to       接受者郵箱
     * @param subject  郵件主題
     * @param context  內(nèi)容類,和模板匹配參數(shù),如下配置id參數(shù)的值為myvaluesitest:
     *                 Context context = new Context();
     *                 context.setVariable("id","myvaluesitest");
     * @param template templates目錄下的模板文件名,如templates/emailTemplate.html則傳:emailTemplate
     */
    public void sendTemplateMail(String from, String to, String subject, IContext context, String template) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            String text = templateEngine.process(template, context);
            helper.setText(text, true);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("Messaging  Exception !", e);
        }
    }

}

5. 測(cè)試類

package com.ljw.task.config;

import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.io.File;

/**
 * @Description: todo
 * @Author: jianweil
 * @date: 2021/11/21 18:45
 */
@SpringBootTest
class EmailTemplateTest {

    @Resource
    private EmailTemplate emailTemplate;
    @Resource
    private MailProperties mailProperties;

    public String getSender() {
        return mailProperties.getUsername();
    }

    public String getReceiver() {
        return mailProperties.getUsername();
    }

    /**
     * 文本
     */
    @Test
    void sendTextMail() {
        emailTemplate.sendTextMail(getSender(), getReceiver(), "標(biāo)題:sendTextMail", "文本內(nèi)容");
    }

    /**
     * 帶html標(biāo)簽
     */
    @Test
    void sendHtmlMail() {
        StringBuffer sb = new StringBuffer();
        sb.append("<h1>大標(biāo)題-h1</h1>")
                .append("<p style='color:#F00'>紅色字</p>")
                .append("<p style='text-align:right'>右對(duì)齊</p>");
        emailTemplate.sendHtmlMail(getSender(), getReceiver(), "標(biāo)題:sendHtmlMail", sb.toString());
    }

    /**
     * 帶附件
     */
    @Test
    void sendAttachmentMail() {
        FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/images/avatar.jpg"));
        emailTemplate.sendAttachmentMail(getSender(), getReceiver(), "標(biāo)題:sendAttachmentMail", "我發(fā)了一個(gè)附件給你注意查收", "附件名.jpg", file);
    }

    /**
     * 發(fā)送內(nèi)聯(lián)資源郵件
     */
    @Test
    void sendInlineResourceMail() {
        String imgId = "avatar";
        String content = "<html><body>宮崎駿電影圖片:<img src='cid:" + imgId + "' ></body></html>";
        FileSystemResource res = new FileSystemResource(new File("src/main/resources/static/images/avatar.jpg"));
        emailTemplate.sendInlineResourceMail(getSender(), getReceiver(), "標(biāo)題:sendInlineResourceMail", content, imgId, res);
    }

    /***
     * 發(fā)送模板郵件
     */
    @Test
    void sendTemplateMail() {
        Context context = new Context();
        context.setVariable("id", "hello");
        emailTemplate.sendTemplateMail(getSender(), getReceiver(), "標(biāo)題:sendTemplateMail", context, "helloTemplate");
    }
}

發(fā)送模板郵件用到的模板類:helloTemplate.html

helloTemplate.html:

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>模板郵件</title>
    </head>
    <body>
        您好,這是模板郵件,請(qǐng)點(diǎn)擊下面的鏈接完成跳轉(zhuǎn),
        <a href="#" th:href="@{'http://www.baidu.com/s?wd='+${id}}">跳轉(zhuǎn)百度</a> <a th:text=" ${id}"></a>。
    </body>
</html>

發(fā)送附件用到的圖片:avatar.jpg

avatar.jpg:

這里就不貼測(cè)試發(fā)送郵件的截圖,發(fā)送人和接收人換成自己郵箱,自己測(cè)試下就行。

6. 常用業(yè)務(wù)分析

  1. 用戶注冊(cè)后需要激活賬號(hào)才能使用的場(chǎng)景:

用戶注冊(cè)成功,保存數(shù)據(jù)到redis,設(shè)置過期時(shí)間,并發(fā)送郵件信息到指定郵箱,該郵件含有用戶唯一標(biāo)識(shí)的key的超鏈接,用戶點(diǎn)擊該超鏈接則回訪到我們的激活接口,驗(yàn)證信息正確則激活。如在設(shè)定時(shí)間內(nèi)沒有點(diǎn)擊激活則激活失敗。

2.其他需要通知的場(chǎng)景

作者:小伙子vae
鏈接:
https://juejin.cn/post/7033215143081148424

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容