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 不會觸發回調。mail.smtp.ssl.enable=true 或 STARTTLS),保護憑證傳輸安全。