在無 Spring 框架的 Struts2 專案中實現郵件發送功能,支援:純文字/HTML 內容、多附件、SMTP 認證、SSL/TLS 加密、中文主題與附件檔名編碼。
<!-- Maven 依賴 -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<!-- activation 在 JDK 9+ 需額外引入 -->
<dependency>
<groupId>com.sun.activation</groupId>
<artifactId>javax.activation</artifactId>
<version>1.2.0</version>
</dependency>
或手動將 mail.jar、activation.jar 放入 WEB-INF/lib。
package com.example.util;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class EMailSender {
private MimeMessage mimeMsg;
private Session session;
private Properties props = new Properties();
private boolean needAuth = false;
private String username, password;
private Multipart mp;
private String lastError;
public EMailSender(String smtpHost) {
setSmtpHost(smtpHost);
createMimeMessage();
}
public void setSmtpHost(String host) {
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25"); // 預設 25,SSL 用 465,STARTTLS 用 587
}
public void setSmtpPort(int port) {
props.put("mail.smtp.port", String.valueOf(port));
}
public void setNeedAuth(boolean need) {
needAuth = need;
props.put("mail.smtp.auth", need ? "true" : "false");
}
public void setAuth(String user, String pwd) {
this.username = user;
this.password = pwd;
}
/** 啟用 SSL (SMTPS) */
public void enableSSL() {
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
}
/** 啟用 STARTTLS */
public void enableStartTLS() {
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
}
private boolean createMimeMessage() {
try {
Authenticator auth = needAuth ? new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
} : null;
session = Session.getInstance(props, auth);
mimeMsg = new MimeMessage(session);
mp = new MimeMultipart("mixed"); // mixed 支援附件 + 內容
return true;
} catch (Exception e) {
lastError = "建立郵件會話失敗: " + e.getMessage();
return false;
}
}
public boolean setSubject(String subject) {
try {
mimeMsg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
return true;
} catch (Exception e) {
lastError = "設定主題失敗: " + e.getMessage();
return false;
}
}
public boolean setBody(String htmlBody) {
try {
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(htmlBody, "text/html; charset=UTF-8");
mp.addBodyPart(bodyPart);
return true;
} catch (Exception e) {
lastError = "設定內容失敗: " + e.getMessage();
return false;
}
}
public boolean addAttachment(String filePath, String fileName) {
try {
MimeBodyPart attachPart = new MimeBodyPart();
DataSource fds = new FileDataSource(filePath);
attachPart.setDataHandler(new DataHandler(fds));
// 解決中文附件檔名亂碼
attachPart.setFileName(MimeUtility.encodeText(fileName, "UTF-8", "B"));
mp.addBodyPart(attachPart);
return true;
} catch (Exception e) {
lastError = "新增附件失敗: " + e.getMessage();
return false;
}
}
public boolean addAttachments(List filePaths) {
for (String path : filePaths) {
if (!addAttachment(path, new java.io.File(path).getName())) return false;
}
return true;
}
public boolean send(String from, String... to) {
try {
mimeMsg.setFrom(new InternetAddress(from));
Address[] toAddrs = new Address[to.length];
for (int i = 0; i < to.length; i++) toAddrs[i] = new InternetAddress(to[i]);
mimeMsg.setRecipients(Message.RecipientType.TO, toAddrs);
mimeMsg.setContent(mp);
mimeMsg.setSentDate(new Date());
Transport.send(mimeMsg);
return true;
} catch (Exception e) {
lastError = "發送失敗: " + e.getMessage();
e.printStackTrace();
return false;
}
}
public String getLastError() { return lastError; }
}
package com.example.action;
import com.example.util.EMailSender;
import com.opensymphony.xwork2.ActionSupport;
public class MailAction extends ActionSupport {
private String to, subject, body;
private List attachments;
private List attachmentsFileName;
private String resultMsg;
public String execute() {
EMailSender sender = new EMailSender("smtp.163.com");
sender.setSmtpPort(465);
sender.enableSSL(); // 163/QQ 等需 SSL
sender.setNeedAuth(true);
sender.setAuth("your@163.com", "auth_code"); // 授權碼非登入密碼
if (sender.setSubject(subject)
&& sender.setBody(body)
&& (attachments == null || sender.addAttachments(
attachments.stream().map(File::getAbsolutePath).collect(Collectors.toList())
))) {
if (sender.send("your@163.com", to.split("[;,]"))) {
resultMsg = "發送成功";
return SUCCESS;
}
}
resultMsg = "發送失敗: " + sender.getLastError();
return ERROR;
}
// getter/setter 省略
}
<action name="sendMail" class="com.example.action.MailAction">
<interceptor-ref name="defaultStack">
<param name="fileUpload.maximumSize">10485760</param> <!-- 10MB -->
</interceptor-ref>
<result name="success">/mail/result.jsp</result>
<result name="error">/mail/error.jsp</result>
</action>
<form action="sendMail" method="post" enctype="multipart/form-data">
收件人: <input name="to" required><br>
主旨: <input name="subject"><br>
內容: <textarea name="body"></textarea><br>
附件: <input type="file" name="attachments" multiple><br>
<input type="submit" value="發送">
</form>
| 問題 | 原因 | 解決 |
|---|---|---|
| 535 Authentication failed | 用密碼而非授權碼、未開啟 SMTP 服務 | 郵箱設定開啟 SMTP/IMAP,生成授權碼 |
| 中文附件檔名亂碼 | 未用 MimeUtility.encodeText | setFileName(MimeUtility.encodeText(name, "UTF-8", "B")) |
| Could not connect to SMTP host | 防火牆/端口/SSL 模式錯誤 | telnet 測試連通性,確認 465/587/25 |
| 大附件發送失敗 | 預設限制/郵箱限制 | 調整 mail.smtp.maxsize、分卷壓縮 |
本方案提供生產級的 EMailSender 工具類,支援 SSL/STARTTLS、中文主題附件、多檔案上傳,無 Spring 依賴,直接整合 Struts2。實務上建議將郵件發送放入非同步佇列(如 JMS/RabbitMQ)避免阻塞請求執行緒。