本文提供一個開箱即用的 JavaMail 發送郵件 Demo,基於 QQ 郵箱 SMTP 服務,採用 SSL (465 端口) + STARTTLS 雙重加密,包含 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+ 支援。
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 略
}
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>");
}
}
session.setDebug(true),控制台會輸出完整 SMTP 交互流程,便於排查認證失敗、證書驗證錯誤等問題。SimpleMailMessage 實體類,支援附件、抄送、密送、內嵌圖片 (CID)。Spring Boot Starter Mail,配合 JavaMailSender 統一管理,支援 Thymeleaf 模板引擎渲染 HTML 內容。@Async + 線程池或消息隊列 (RabbitMQ/Kafka) 解耦發送流程,提升主業務響應速度。JavaMail 整合 QQ 郵箱發送郵件的核心在於:正確的 SSL/TLS 參數 + 有效授權碼 + 合理的發送頻控。本文提供的 Demo 經實測可直接跑通,作為項目中郵件通知模組的起步代碼完全足夠。