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

JavaMail 安全認證實作:自定義 Authenticator

     編輯:Java 相關知識

JavaMail 發送郵件時,SMTP 服務器常要求身份驗證。通過繼承 javax.mail.Authenticator 並覆寫 getPasswordAuthentication(),即可在 Session 建立連接時自動提供憑證。

核心代碼

import javax.mail.*;

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() {
        // Session 會在需要認證時自動回調此方法
        return new PasswordAuthentication(username, password);
    }
}

使用方式

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");

Session session = Session.getInstance(props, new MailAuthenticator("user", "pwd"));
Message msg = new MimeMessage(session);
// ... 設置收發件人、主題、內容
Transport.send(msg);

關鍵點

  • mail.smtp.auth=true 必須開啟,否則 Session 不會觸發回調。
  • Authenticator 實例通常作為單例或隨 Session 生命週期,避免重複創建。
  • 生產環境建議啟用 SSL/TLS(mail.smtp.ssl.enable=true 或 STARTTLS),保護憑證傳輸安全。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved