JavaMail 是 Sun Microsystems 發布的標準 Java API,專門用於處理電子郵件的發送、接收與解析。它提供了一組獨立於協議的抽象類,支援 SMTP、POP3、IMAP 等主流郵件協議,讓開發者能以統一介面實現郵件傳輸功能,無需深入了解底層協議細節。
雖然 JavaMail 屬於 Sun 官方 API,但並未包含在標準 JDK 中,使用前需額外下載。此外,JavaMail 運行還依賴 JavaBeans Activation Framework (JAF),該框架負責處理 MIME 資料類型的識別與操作。在 Windows 2000 等舊系統上需手動配置類路徑指向這兩個 JAR 包;現代開發環境建議使用 Maven 或 Gradle 管理依賴:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
JavaMail 的核心類位於 javax.mail 套件,主要組件包括:
MimeMessage,封裝發件人、收件人、主題、正文及附件。首先建立一個 HTML 表單收集郵件資訊,採用 POST 方式提交至 JSP 處理頁:
<form action="sendmail.jsp" method="post">
<table align="center">
<tr>
<td>收件人:<br><input name="to" size="40"></td>
<td>寄件人:<br><input name="from" size="40"></td>
</tr>
<tr>
<td colspan="2">主題:<br><input name="subject" size="60"></td>
</tr>
<tr>
<td colspan="2">內容:<br><textarea name="content" rows="10" cols="80"></textarea></td>
</tr>
</table>
<input type="submit" value="發送"> <input type="reset" value="重填">
</form>
在 sendmail.jsp 中接收參數並調用 JavaMail API:
<%@ page import="javax.mail.*, javax.mail.internet.*, java.util.Properties" %>
<%
String to = request.getParameter("to");
String from = request.getParameter("from");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
// 1. 配置郵件會話屬性
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com"); // SMTP 伺服器
props.put("mail.smtp.port", "587"); // 提交埠
props.put("mail.smtp.auth", "true"); // 需認證
props.put("mail.smtp.starttls.enable", "true"); // 啟用 TLS
// 2. 建立認證器
Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
};
// 3. 獲取 Session 實例
Session session = Session.getInstance(props, auth);
try {
// 4. 構建 MIME 郵件
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 java.util.Date());
// 5. 發送郵件
Transport.send(msg);
out.println("<script>alert('郵件發送成功!');</script>");
} catch (MessagingException e) {
out.println("<script>alert('發送失敗:" + e.getMessage() + "');</script>");
e.printStackTrace();
}
%>
使用 MimeMultipart 組合純文字與 HTML 版本,確保郵件客戶端相容性:
MimeMultipart multipart = new MimeMultipart("alternative");
BodyPart textPart = new MimeBodyPart();
textPart.setText("純文字備用內容", "UTF-8");
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<h1>HTML 內容</h1><p>支援樣式</p>", "text/html; charset=UTF-8");
multipart.addBodyPart(textPart);
multipart.addBodyPart(htmlPart);
msg.setContent(multipart);
MimeBodyPart attachment = new MimeBodyPart();
DataSource source = new FileDataSource("/path/to/file.pdf");
attachment.setDataHandler(new DataHandler(source));
attachment.setFileName(MimeUtility.encodeText("報表.pdf"));
multipart.addBodyPart(attachment);
生產環境建議採用非同步方式(如 @Async 或消息佇列)避免阻塞請求執行緒,並完善異常捕獲、日誌記錄與重試機制。同時注意郵件伺服器的發送頻率限制,防止被判定為垃圾郵件發送者。
MimeUtility.encodeText 編碼。mail.smtp.ssl.enable 或 mail.smtp.starttls.enable 設定。JavaMail 為 Java 應用提供了強大且靈活的郵件處理能力。在 JSP 中整合時,關鍵在於正確配置 Session 屬性、妥善構建 MimeMessage、妥善處理異常與編碼。現代開發建議將郵件發送邏輯封裝為獨立 Service 層,配合 Spring Mail 或獨立工具類使用,提升代碼可維護性與測試性。