DEBUG SMTP: AUTH LOGIN failed
javax.mail.AuthenticationFailedException: 535 Error: authentication failed
代碼邏輯正確、依賴包完整(activation-1.1.1.jar、javax.mail-1.5.4.jar),但認證通不過。
主流郵箱服務商(163、126、QQ、Gmail 等)已關閉預設 SMTP 密碼登入,需開啟專用授權碼。
// 錯誤:使用登入密碼
MyAuthenticator myauth = new MyAuthenticator(from, "登入密碼");
// 正確:使用客戶端授權碼
MyAuthenticator myauth = new MyAuthenticator(from, "授權碼_xxxxxxxxxxxxxxxx");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.port", "25"); // 或 465(SSL), 587(STARTTLS)
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("你的郵箱@163.com", "授權碼");
}
});
session.setDebug(true); // 開啟調試輸出
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("你的郵箱@163.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("收件箱"));
message.setSubject("測試主題");
message.setText("測試內容");
Transport.send(message);
| 端口 | 協議 | 備註 |
|---|---|---|
| 25 | SMTP | 明文/STARTTLS,部分 ISP 封鎖 |
| 465 | SMTPS | SSL 加密,需 mail.smtp.ssl.enable=true |
| 587 | Submission | STARTTLS,推薦現代標準 |
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.port", "465");
郵箱登入密碼 ≠ SMTP 授權碼。授權碼專供第三方客戶端/程式使用,可單獨撤銷,安全性更高。