1. 程式人生 > 其它 >j內建物件2

j內建物件2

1. pom

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

2.application.properties

#這裡以qq郵箱為例
# qq郵箱伺服器
spring.mail.host=smtp.qq.com
# 你的qq郵箱賬戶
[email protected]
# 你的qq郵箱第三方授權碼
spring.mail.password=yourPassword
# 編碼型別
spring.mail.default-encoding=UTF-8

3. 開啟郵箱第三方支援以及獲取授權碼(以QQ郵箱為例)

4. 程式碼編寫

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author [email protected]
 * @create 2022-01-11 19:22
 * @Description
 */
@Service
public class MailUtils {
    // 日誌
    private final Logger logger = LoggerFactory.getLogger(MailUtils.class);
    @Value("${spring.mail.username}") //注入 application.properties中指定的使用者名稱
    private String from;

    @Autowired //用於傳送檔案
    private JavaMailSender mailSender;


    /**
     * 傳送普通文字郵件
     *
     * @param to      收件人
     * @param subject 主體
     * @param content 內容
     */
    public void sendSimpleMail(
            String to, String subject, String content
    ) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);//收信人
        message.setSubject(subject);//主題
        message.setText(content);//內容
        message.setFrom(from);//發信人

        mailSender.send(message);
    }

    /**
     * 傳送html郵件
     *
     * @param to      收件人
     * @param subject 書體
     * @param content 內容(可以包含html等標籤)
     */
    public void sendHtmlMail(
            String to, String subject, String content
    ) {
        //使用MimeMessage,MIME協議
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper;
        //MimeMessageHelper幫助我們設定更豐富的內容
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);//true代表支援html
            mailSender.send(message);
            logger.info("傳送HTML郵件成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.error("傳送HTML郵件失敗:", e);
        }

    }


    /**
     * 傳送帶附件的郵件
     *
     * @param to       收件人
     * @param subject  主體
     * @param content  內容
     * @param filePath 附件路徑
     */
    public void sendAttachmentMail(
            String to, String subject,
            String content, String filePath
    ) {
        // 日誌
        logger.info("傳送帶附件郵件開始:{},{},{},{}", to, subject, content, filePath);
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            //true代表支援多元件,如附件,圖片等
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);//新增附件,可多次呼叫該方法新增多個附件
            mailSender.send(message);
            logger.info("傳送帶附件郵件成功");
        } catch (MessagingException e) {
            logger.error("傳送帶附件郵件失敗", e);
        }

    }

    /**
     * 傳送帶圖片的郵件
     *
     * @param to      收件人
     * @param subject 主體
     * @param content 內容
     * @param rscPath 圖片路徑
     * @param rscId   rscId 圖片ID,用於在<img\>標籤中使用,從而顯示圖片
     */
    public void sendInlineResourceMail(
            String to, String subject, String content,
            String rscPath, String rscId) {
        // 日誌
        logger.info("傳送帶圖片郵件開始:{},{},{},{},{}", to, subject, content, rscPath, rscId);
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);//重複使用新增多個圖片
            mailSender.send(message);
            logger.info("傳送帶圖片郵件成功");
        } catch (MessagingException e) {
            logger.error("傳送帶圖片郵件失敗", e);
        }
    }
}

5. 測試

/**
 * @author [email protected]
 * @create 2022-01-11 19:49
 * @Description
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTest {
    @Autowired
    MailUtils mailUtils;

    /**
     * 傳送簡單純文字郵件
     */
    @Test
    public void sendSimpleMail() {
        mailUtils.sendSimpleMail("[email protected]", "傳送郵件測試", "大家好,這是我用springboot進行傳送郵件測試");
    }

    /**
     * 傳送HTML郵件
     */
    @Test
    public void sendHtmlMail() {
        String content = "<html><body><h3><font color=\"red\">" + "大家好,這是springboot傳送的HTML郵件" + "</font></h3></body></html>";
        mailUtils.sendHtmlMail("[email protected]", "傳送郵件測試", content);
    }

    /**
     * 傳送帶附件的郵件
     */
    @Test
    public void sendAttachmentMail() {
        String content = "<html><body><h3><font color=\"red\">" + "大家好,這是springboot傳送的HTML郵件,有附件哦" + "</font></h3></body></html>";
        String filePath = "your file path";
        mailUtils.sendAttachmentMail("[email protected]", "傳送郵件測試", content, filePath);
    }

    /**
     * 傳送帶圖片的郵件
     */
    @Test
    public void sendInlineResourceMail() {
        String rscPath = "your picture path";
        String rscId = "001";
        String content = "<html><body><h3><font color=\"red\">" + "大家好,這是springboot傳送的HTML郵件,有圖片哦" + "</font></h3>"
                + "<img src=\'cid:" + rscId + "\'></body></html>";
        mailUtils.sendInlineResourceMail("[email protected]", "傳送郵件測試", content, rscPath, rscId);
    }
}

6. 傳送模板郵件

  • 以Thymeleaf模板引擎為例來講解(具體語法自行了解)

6.0 匯入 thymeleaf依賴

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

6.1 在templates資料夾下建立emailTemplate.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>郵件模板</title>
</head>
<body>
您好,感謝您的註冊,這是一封驗證郵件,請點選下面的連結完成註冊,感謝您的支援!<br>
<a href="#" th:href="@{http://www.bestbpf.com/register/{id}(id=${id})}">啟用賬戶</a>
</body>
</html>

6.2 測試

    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    MailUtils mailUtils;

    /**
     * 指定模板傳送郵件
     */
    /**
     * 指定模板傳送郵件
     */
    @Test
    public void testTemplateMail() {
        //向Thymeleaf模板傳值,並解析成字串
        Context context = new Context();
        context.setVariable("id", "001");
        String emailContent = templateEngine.process("emailTemplate", context);
        mailUtils.sendHtmlMail("[email protected]", "這是一個模板檔案", emailContent);
    }

參考
https://www.jianshu.com/p/59d15b357201