JavaMail API 以四大核心對象封裝郵件發送全流程:
<%@ page import="javax.mail.*, javax.mail.internet.*, javax.activation.*, java.util.*" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<html><body>
<h2>JavaMail 郵件發送測試</h2>
<%
// 1. 配置屬性
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com"); // SMTP 服務器
props.put("mail.smtp.port", "25"); // 端口 (25/465/587)
props.put("mail.smtp.auth", "true"); // 需要認證
// SSL 配置 (如 465 端口)
// props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// props.put("mail.smtp.socketFactory.port", "465");
// props.put("mail.smtp.socketFactory.fallback", "false");
// TLS 配置 (如 587 端口 STARTTLS)
// props.put("mail.smtp.starttls.enable", "true");
// 2. 創建 Session (無需 Authenticator 若僅發送)
Session session = Session.getInstance(props, null);
session.setDebug(true); // 控制台輸出 SMTP 交互日誌,調試必備
// 3. 構建 MimeMessage
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("sender@example.com", "發件人名稱", "UTF-8"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recipient1@example.com, recipient2@example.com"));
msg.setSubject("測試郵件主題", "UTF-8");
msg.setSentDate(new Date());
// 4. 設置純文本正文
msg.setText("這是純文本郵件正文內容。", "UTF-8");
// 或設置 HTML 正文: msg.setContent("HTML 內容
", "text/html;charset=UTF-8");
// 5. 發送
Transport transport = session.getTransport("smtp");
transport.connect("smtp.example.com", "username", "password"); // 顯式連接認證
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
out.println("<font color='green'>郵件發送成功!</font>");
%>
</body></html>
// 構建多部分郵件
MimeMultipart multipart = new MimeMultipart("mixed"); // mixed: 附件; related: 內嵌圖片; alternative: 文本/HTML 替代
// 1. HTML 正文部分
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<h1>你好</h1><p>內嵌圖片: <img src='cid:image001'></p>", "text/html;charset=UTF-8");
multipart.addBodyPart(htmlPart);
// 2. 內嵌圖片部分 (related 子集)
MimeBodyPart imagePart = new MimeBodyPart();
DataSource fds = new FileDataSource("/path/to/logo.png");
imagePart.setDataHandler(new DataHandler(fds));
imagePart.setHeader("Content-ID", "<image001>"); // CID 引用
imagePart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(imagePart);
// 3. 附件部分
MimeBodyPart attachPart = new MimeBodyPart();
DataSource attachSrc = new FileDataSource("/path/to/report.pdf");
attachPart.setDataHandler(new DataHandler(attachSrc));
attachPart.setFileName(MimeUtility.encodeText("報告.pdf", "UTF-8", "B")); // 編碼中文文件名
attachPart.setDisposition(MimeBodyPart.ATTACHMENT);
multipart.addBodyPart(attachPart);
// 4. 設置到 Message
msg.setContent(multipart);
<%@ page import="javax.mail.*, javax.mail.internet.*, javax.activation.*, java.util.*" %>
<%
String to = request.getParameter("to");
String subject = request.getParameter("subject");
String text = request.getParameter("text");
String from = request.getParameter("from"); // 或固定配置
// 基本校驗
if (to == null || to.trim().isEmpty()) {
out.println("收件人不能為空");
return;
}
try {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.auth", "true");
// ... 其他配置
Session session = Session.getInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
msg.setSubject(subject, "UTF-8");
msg.setText(text, "UTF-8");
msg.setSentDate(new Date());
Transport transport = session.getTransport("smtp");
transport.connect("username", "password");
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
out.println("郵件已發送至: " + to);
} catch (MessagingException e) {
out.println("發送失敗: " + e.getMessage());
e.printStackTrace(); // 日誌記錄
} catch (Exception e) {
out.println("系統錯誤: " + e.getMessage());
}
%>
| 參數名 | 說明 | 典型值 |
|---|---|---|
| mail.smtp.host | SMTP 服務器地址 | smtp.qq.com, smtp.gmail.com, smtp.exmail.qq.com |
| mail.smtp.port | SMTP 端口 | 25 (明文), 465 (SSL), 587 (STARTTLS) |
| mail.smtp.auth | 是否認證 | true |
| mail.smtp.socketFactory.class | SSL Socket 工廠 | javax.net.ssl.SSLSocketFactory (465 端口必填) |
| mail.smtp.socketFactory.port | SSL 端口 | 465 |
| mail.smtp.starttls.enable | 啟用 STARTTLS | true (587 端口) |
| mail.smtp.timeout | Socket 讀取超時 (ms) | 10000 |
| mail.smtp.connectiontimeout | 連接超時 (ms) | 10000 |
| mail.debug | 調試輸出 | true/false |
InternetAddress(addr, name, "UTF-8"), setSubject(subj, "UTF-8"), setText(text, "UTF-8"), MimeUtility.encodeText(filename, "UTF-8", "B")。com.sun.activation:javax.activation:1.2.0。JavaMailSender (內部管理連接)。JavaMail 以 Properties -> Session -> MimeMessage -> Transport 四步封裝了 SMTP 協議細節。掌握 MimeMultipart 構建富文本/附件郵件、SSL/TLS 配置、中文編碼處理、異常排查,是 Java 開發者實現「郵件通知」功能的必備技能。生產環境務必採用**異步發送 + 模板引擎 + 重試審計**架構。