JavaMail API 是發送郵件的標準工具。本文提供基於 SSL 的完整發送代碼,並總結 QQ/163 郵箱的關鍵配置差異與高頻錯誤碼排查指南。
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
public class MailUtil {
public static String send(String username, String authCode, String from,
String to, String subject, String content, String host) {
Properties props = new Properties();
props.put("mail.smtp.host", host); // smtp.qq.com / smtp.163.com
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", "smtp");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, authCode);
}
});
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
msg.setSubject(subject, "UTF-8");
msg.setText(content, "UTF-8");
msg.setSentDate(new Date());
Transport.send(msg);
return "SUCCESS";
} catch (MessagingException e) {
return e.getMessage();
}
}
}
authCode 參數。smtp.qq.com,163 → smtp.163.com。| 代碼 | 含義 | 排查方向 |
|---|---|---|
| 535 | 認證失敗 | 授權碼過期/錯誤、用戶名錯誤、未開啟 SMTP |
| 550 DT:SPM | 垃圾郵件特徵 | 優化正文內容、添加退訂鏈接、控制發送頻率 |
| 421 HL:ICC | 並發連接超限 | 降低並發數、增加發送間隔 |
| 451 DT:SPM | 臨時拒收 | 兩分鐘後重試、調整內容或發送環境 |
| 554 IP in blacklist | IP 被封禁 | 檢查 IP 信譽、更換發送 IP、聯繫郵箱服務商 |
| 552 | 附件/大小超限 | 壓縮附件、分卷發送、避免禁用後綴 |
msg.setRecipients(Message.RecipientType.BCC, ...) 隱藏收件人。msg.setContent(html, "text/html;charset=UTF-8")。MimeMultipart,添加 MimeBodyPart 附件。掌握協議配置、授權碼機制與錯誤碼語義,能讓 Java 郵件發送從「能跑通」進化為「穩定可觀測、故障可快速定位」的生產級能力。