首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring Boot 實現郵件發送功能完整指南

     編輯:Java 相關知識

Spring Boot 整合 JavaMail 發送郵件實戰教學

在企業級應用開發中,郵件通知功能幾乎是標配需求。Spring Boot 透過 spring-boot-starter-mail 提供了開箱即用的郵件發送支援,本文將完整示範從依賴引入、配置設定到程式碼實作的完整流程。

1. 引入 Maven 依賴

在 pom.xml 中加入郵件啟動器依賴:

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

2. 設定 application.properties 郵件參數

以 QQ 郵箱 SMTP 服務為例,關鍵配置說明:

  • spring.mail.host:SMTP 伺服器地址(QQ 郵箱為 smtp.qq.com)
  • spring.mail.username:完整郵箱地址
  • spring.mail.password:授權碼而非登入密碼(需在郵箱設定中開啟 SMTP 服務獲取)
  • spring.mail.properties.mail.smtp.auth:啟用身份驗證
  • spring.mail.properties.mail.smtp.starttls.enable:啟用 TLS 加密傳輸
spring.thymeleaf.cache=false
spring.mail.host=smtp.qq.com
spring.mail.username=your_email@qq.com
spring.mail.password=your_authorization_code
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

3. 實作 MailService 服務層

封裝簡單郵件發送邏輯,注入 JavaMailSender:

@Service
public class MailService {
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender sender;

    public void sendSimple(String to, String title, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(title);
        message.setText(content);
        sender.send(message);
        System.out.println("郵件發送成功");
    }
}

4. 建立前端測試頁面

使用 Thymeleaf 模板引擎建立簡單表單:

<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>郵件發送測試</title>
</head>
<body>
    <h1>郵件發送測試頁面</h1>
    <form action="sendMail" method="post">
        <p>郵件主旨: <input type="text" name="title"/></p>
        <p><input type="submit" value="發送郵件"/></p>
    </form>
</body>
</html>

5. 控制器處理請求

@Controller
public class MailController {
    @Autowired
    private MailService mailService;

    private String to = "recipient@qq.com";

    @RequestMapping("mail")
    public String mail() {
        return "mail";
    }

    @RequestMapping("sendMail")
    @ResponseBody
    public String sendMail(@RequestParam("title") String title) {
        mailService.sendSimple(to, title, "這是測試郵件內容:" + title);
        return "success";
    }
}

6. QQ 郵箱授權碼獲取步驟

  1. 登入 QQ 郵箱網頁版 → 設定 → 帳戶
  2. 找到「POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV 服務」區塊
  3. 開啟「IMAP/SMTP 服務」
  4. 按提示發送簡訊驗證,即可獲得 16 位授權碼
  5. 將授權碼填入 spring.mail.password

QQ郵箱開啟SMTP服務 獲取授權碼

7. 進階應用建議

  • HTML 郵件:使用 MimeMessageHelper 支援 HTML 內容、附件、內嵌圖片
  • 異步發送:配合 @Async 註解避免阻塞主執行緒
  • 模板引擎:整合 Thymeleaf 或 FreeMarker 實現動態郵件模板
  • 發送重試:引入 Spring Retry 處理暫時性網路失敗

掌握 Spring Boot 郵件發送後,可輕鬆擴展至註冊驗證、密碼重設、訂單通知等實際業務場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved