JavaMail 核心組件
- Session:郵件會話,持有認證、協議配置(SMTP/IMAP/POP3)
- Message (MimeMessage):郵件實體,包含發件人、收件人、主題、內容、附件
- Transport:發送協議實現(SMTP)
- Store:接收協議實現(IMAP/POP3)
- Authenticator:SMTP 認證回調
環境準備
- 下載 Jakarta Mail(原 JavaMail):
jakarta.mail-2.0.1.jar
- 下載 Jakarta Activation(JDK 9+ 必需):
jakarta.activation-2.0.1.jar
- 放入
WEB-INF/lib 或 Maven 依賴:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>2.0.1</version>
</dependency>
郵件發送完整 Servlet/JSP 實現
1. 郵件發送工具類
package com.example.util;
import jakarta.mail.*;
import jakarta.mail.internet.*;
import java.util.Properties;
public class MailUtil {
private static final String SMTP_HOST = "smtp.example.com";
private static final int SMTP_PORT = 587; // TLS
private static final String USERNAME = "noreply@example.com";
private static final String PASSWORD = "your_smtp_password";
public static void sendMail(String to, String subject, String htmlContent, File... attachments) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true"); // TLS
props.put("mail.smtp.ssl.trust", SMTP_HOST);
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USERNAME, PASSWORD);
}
});
session.setDebug(false); // 開發時可設 true 看協議日誌
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(USERNAME, "系統通知", "UTF-8"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
msg.setSubject(subject, "UTF-8");
msg.setSentDate(new java.util.Date());
// 構建多部分內容:HTML + 附件
Multipart mp = new MimeMultipart();
// HTML 正文
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlContent, "text/html;charset=UTF-8");
mp.addBodyPart(htmlPart);
// 附件
if (attachments != null) {
for (File file : attachments) {
MimeBodyPart attachPart = new MimeBodyPart();
attachPart.attachFile(file);
attachPart.setFileName(MimeUtility.encodeText(file.getName(), "UTF-8", "B"));
mp.addBodyPart(attachPart);
}
}
msg.setContent(mp);
Transport.send(msg);
}
}
2. 前端表單 (sendmail.jsp)
<%@ page contentType="text/html;charset=UTF-8" %>
<html><body>
<h2>發送郵件</h2>
<form action="sendMail.jsp" method="post" enctype="multipart/form-data">
收件人: <input name="to" type="email" required><br>
主旨: <input name="subject" required><br>
內容 (HTML):<br>
<textarea name="content" rows="10" cols="60"></textarea><br>
附件: <input name="attach" type="file"> (可多檔)<br>
<input type="submit" value="發送">
</form>
</body></html>
3. 處理頁 (sendMail.jsp)
<%@ page import="com.example.util.MailUtil, jakarta.servlet.http.Part, java.io.*, java.util.*" %>
<%
request.setCharacterEncoding("UTF-8");
String to = request.getParameter("to");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
// 處理上傳附件(Servlet 3.0+)
Collection parts = request.getParts();
List tempFiles = new ArrayList<>();
for (Part part : parts) {
if ("attach".equals(part.getName()) && part.getSize() > 0) {
File temp = File.createTempFile("mail_attach_", "_" + part.getSubmittedFileName());
part.write(temp.getAbsolutePath());
tempFiles.add(temp);
}
}
try {
MailUtil.sendMail(to, subject, content, tempFiles.toArray(new File[0]));
out.println("<script>alert('發送成功!'); history.back();</script>");
} catch (Exception e) {
e.printStackTrace();
out.println("<script>alert('發送失敗:" + e.getMessage().replace("'", "\\'") + "'); history.back();</script>");
} finally {
for (File f : tempFiles) f.delete(); // 清理臨時文件
}
%>
常見問題與解決
| 問題 | 原因 | 解決 |
| 535 Authentication failed | 帳密錯誤、未開啟 SMTP、需應用專用密碼 | 檢查郵箱設置、生成 App Password (Gmail/Outlook) |
| Could not connect to SMTP host | 端口錯誤、防火牆、SSL/TLS 不匹配 | 465(SSL) / 587(STARTTLS) / 25(明文),確認 props 設置 |
| 中文附件名亂碼 | RFC 2231 編碼缺失 | MimeUtility.encodeText(name, "UTF-8", "B") |
| 大附件發送失敗 | 超過郵箱限制 (通常 25MB) | 分卷壓縮、雲盤分享連結、對象存儲預簽名 URL |
| 發送緩慢/超時 | 同步阻塞、DNS 解析慢 | 異步隊列、連線池、預解析 SMTP 域名 |
進階主題
- 郵件模板引擎:FreeMarker/Thymeleaf 渲染 HTML 郵件
- 批量發送:BCC 隱藏收件人、分批發送、速率限制
- 退信/打開追蹤:VERP、像素點追蹤、Webhook 回調
- DKIM/SPF/DMARC:提升送達率、防偽造
- Spring Boot 整合:
spring-boot-starter-mail + JavaMailSender 一鍵配置