SpringBoot QQ郵箱發送郵件實例代碼

SpringBoot整合郵件任務(QQ郵箱發送)

1.獲取QQ郵箱授權碼

在這裡插入圖片描述

2.導入郵箱發送依賴啟動器

使用定制郵件模板的方法實現通用郵件發送,Thymeleaf構建郵件模板需要一起導入依賴。

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

        <!-- thymeleaf模板依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

3.配置文件yml添加郵件服務配置

# Spring配置
spring:
  mail:
    host: smtp.qq.com
    username: ********@qq.com
    # password是第一步QQ郵箱開通的smtp服務後得到的客戶端授權碼
    password: ******************
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
#thymeleaf模板引擎配置太簡單,就不貼出來瞭

4.編寫接口IMailService

public interface IMailService {
    void sendHtmlMailThymeLeaf(String mailFrom, String mailFromNick, String mailTo, String cc, String subject, String content);
}

5.編寫實現MailServiceImpl

@Service
public class MailServiceImpl implements IMailService {

    /**
     * JavaMailSender是Spring Boot在MailSenderPropertiesConfiguration 類中配直好的,該類在 Mail
     * 自動配置類 MailSenderAutoConfiguration 中導入 因此這裡註入 JavaMailSender 就可以使用瞭
     */
    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void sendHtmlMailThymeLeaf(String mailFrom, String mailFromNick, String mailTo, String cc, String subject, String content) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(new InternetAddress(mailFromNick + " <" + mailFrom + ">"));
            // 設置多個收件人
            String[] toAddress = mailTo.split(",");
            mimeMessageHelper.setTo(toAddress);
            if (!StringUtils.isEmpty(cc)) {
                mimeMessageHelper.setCc(cc);
            }
            mimeMessageHelper.setSubject(subject);
            // 第二個參數為true表示郵件正文是html格式的,默認是false
            mimeMessageHelper.setText(content, true);

            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            System.out.println(e);
        }

    }
}

6.Controller調用

    // 發件人要跟yml配置文件裡填寫的郵箱一致
    String mailFrom = "******@qq.com";
    // 收件人
    String mailTo = "******@qq.com,******@qq.com";
    // 抄送(可為空)
    String cc = "******@qq.com";


    // 註入mailService
    @Autowired
    private IMailService mailService;
  
    // 註入TemplateEngine
    @Autowired
    TemplateEngine templateEngine;

    @RequestMapping("/other/test")//請求路徑
    @ResponseBody
    public void testMail() {

        //註意1:這裡我是查詢對應的內容,使用富文本編輯器存儲html標簽的內容
        Strategy strategy = strategyService.selectStrategyByStrategyId(Long.valueOf(1));
       
        Context context = new Context(); // 導包是org.thymeleaf.context
        //註意2:獲取發送的內容傳入thymeleaf模板中
        context.setVariable("content", strategy.getStrategyContent());

        String content = templateEngine.process("mailTemplate.html", context);
        //System.out.println(content);

        mailService.sendHtmlMailThymeLeaf(mailFrom, "定義發件人名字", mailTo, cc, "定義郵件標題", content);

        System.out.println("郵件發送成功");
    }

7.thymeleaf模板 mailTemplate.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>郵件發送</title>
</head>

<body>
    <!--使用富文本框包含HTML標簽 使用 th:utext標簽 會解析html,顯示相應的效果-->
<div th:utext="${content}">Some escaped text</div>

</body>

</html>

總結

到此這篇關於SpringBoot QQ郵箱發送郵件實例代碼的文章就介紹到這瞭,更多相關SpringBoot 郵箱發信內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: