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

JavaMail 實戰:基於 QQ 郵箱 SMTP 發送郵件完整 Demo (含 SSL/TLS 配置)

     編輯:Java 綜合教學

JavaMail 整合 QQ 郵箱發送郵件實戰指南

本文提供一個開箱即用的 JavaMail 發送郵件 Demo,基於 QQ 郵箱 SMTP 服務,採用 SSL (465 端口) + STARTTLS 雙重加密,包含 Maven 依賴、認證器封裝、發送核心類與測試主程式,並針對騰訊郵箱的「獨立授權碼」、「發送頻率限制」等坑點給出避坑指南。

一、Maven 依賴配置

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.1</version>
</dependency>

提示:生產環境建議升級至 jakarta.mail:jakarta.mail-api:2.x 並搭配 com.sun.mail:jakarta.mail 實現包,獲得更好的 TLS 1.2+ 支援。

二、核心組件實現

1. 郵箱認證器

public class MailAuthenticator extends Authenticator {
    private final String username;
    private final String password;

    public MailAuthenticator(String username, String password) {
        this.username = username;
        this.password = password;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
    // getter/setter 略
}

2. 郵件發送器

public class SimpleMailSender {
    private final Properties props = System.getProperties();
    private MailAuthenticator authenticator;
    private Session session;

    /** 完整構造器:指定 SMTP 主機 */
    public SimpleMailSender(String smtpHost, String username, String password)
            throws NoSuchProviderException {
        init(username, password, smtpHost);
    }

    /** 便利構造器:從郵箱地址自動推導 smtp.host (smtp.qq.com) */
    public SimpleMailSender(String username, String password)
            throws NoSuchProviderException {
        String host = "smtp." + username.split("@")[1];
        init(username, password, host);
    }

    private void init(String username, String password, String smtpHost)
            throws NoSuchProviderException {
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtpHost);
        // QQ 郵箱 SSL 端口
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.starttls.enable", "true");

        authenticator = new MailAuthenticator(username, password);
        session = Session.getInstance(props, authenticator);
        session.setDebug(true); // 開啟調試日誌
    }

    /** 發送 HTML 郵件 */
    public void send(String recipient, String subject, Object content)
            throws AddressException, MessagingException {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(authenticator.getUsername()));
        message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
        message.setSubject(subject, "UTF-8");
        message.setContent(content.toString(), "text/html;charset=UTF-8");
        Transport.send(message);
    }

    public static void main(String[] args) throws Exception {
        // 注意:這裡的密碼必須是 QQ 郵箱「設置→賬戶→開啟 SMTP 服務」生成的 16 位授權碼,而非登錄密碼
        SimpleMailSender sender = new SimpleMailSender("your_qq@qq.com", "auth_code_16_chars");
        sender.send("target@qq.com", "測試主題", "<h3>Hello JavaMail</h3>");
    }
}

三、騰訊郵箱避坑指南 (必讀)

  1. 授權碼 ≠ 登錄密碼:必須在 QQ 郵箱網頁端「設置→賬戶」開啟 POP3/SMTP/IMAP 服務,獲取 16 位授權碼作為 JavaMail 密碼。
  2. 端口與加密:騰訊企業郵/個人郵均強制要求 SSL (465) 或 STARTTLS (587),純文本 25 端口已封禁。
  3. 發送頻率限制:短時間大量發送會觸發連接斷開 (read timed out / connection reset),建議:
    • 單連接發送間隔 ≥ 5 秒
    • 批量發送採用連接池或異步隊列
    • 重要業務自建郵件服務器或使用 SendCloud、Mailgun 等專業服務
  4. Debug 模式:開發階段保持 session.setDebug(true),控制台會輸出完整 SMTP 交互流程,便於排查認證失敗、證書驗證錯誤等問題。

四、進階擴展建議

  • 封裝 SimpleMailMessage 實體類,支援附件、抄送、密送、內嵌圖片 (CID)。
  • 引入 Spring Boot Starter Mail,配合 JavaMailSender 統一管理,支援 Thymeleaf 模板引擎渲染 HTML 內容。
  • 異步化:@Async + 線程池或消息隊列 (RabbitMQ/Kafka) 解耦發送流程,提升主業務響應速度。
  • 重試機制:指數退避 + 死信隊列,保證郵件最終送達。

總結

JavaMail 整合 QQ 郵箱發送郵件的核心在於:正確的 SSL/TLS 參數 + 有效授權碼 + 合理的發送頻控。本文提供的 Demo 經實測可直接跑通,作為項目中郵件通知模組的起步代碼完全足夠。

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