| 類 | 作用 | 關鍵方法 |
| Properties | 配置郵件會話屬性 (SMTP 主機等) | put("mail.smtp.host", "smtp.xxx.com") |
| Session | 郵件會話上下文,單例或多實例 | getInstance(props, authenticator) |
| MimeMessage | MIME 郵件對象,構建郵件結構 | setFrom(), setRecipients(), setSubject(), setContent() |
| Transport | 郵件傳輸協議實現 (SMTP) | send(message) |
可復用 Mail JavaBean 設計
封裝發件人、收件人、主題、SMTP 服務器、附件集合,提供 attachFile() 收集附件,startSend() 執行發送。
public class Mail {
private String to, from, host, subject;
private Vector attachments = new Vector<>();
public Mail(String to, String from, String smtpServer, String subject) { ... }
public void attachFile(String fileName) { attachments.add(fileName); }
public boolean startSend() {
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
Session session = Session.getDefaultInstance(props, null);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,
new InternetAddress[] { new InternetAddress(to) });
msg.setSubject(subject);
// 構建多部分內容:每個附件一個 MimeBodyPart
Multipart mp = new MimeMultipart();
for (String file : attachments) {
MimeBodyPart mbp = new MimeBodyPart();
FileDataSource fds = new FileDataSource(file);
mbp.setDataHandler(new DataHandler(fds));
mbp.setFileName(fds.getName());
mp.addBodyPart(mbp);
}
attachments.clear();
msg.setContent(mp);
msg.setSentDate(new Date());
Transport.send(msg);
return true;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
}
}
關鍵點解析
- Multipart / MimeBodyPart:MIME 多部分消息結構,每個附件獨立封裝
- FileDataSource + DataHandler:標準方式讀取文件並編碼為郵件體
- setFileName():保留原始文件名,接收端正確顯示
- 異常處理:捕獲
MessagingException 及鏈式異常,返回失敗狀態
輕量級 Servlet 整合示例
public class SendMailServlet extends HttpServlet implements SingleThreadModel {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try {
Mail mail = new Mail("zhang@263.net", "chtwoy@21cn.com",
"smtp.21cn.com", "測試附件郵件");
mail.attachFile("table.pdf"); // 可多次調用添加多個附件
mail.startSend();
} catch (Exception e) {
e.printStackTrace();
}
}
}
部署與使用提示
- 下載 JavaMail API (javax.mail.jar) 及 JavaBeans Activation Framework (activation.jar),放入
WEB-INF/lib 或容器共享庫
- 確保 SMTP 服務器地址、賬號密碼正確(部分服務器需認證,可通過
Session.getInstance(props, new Authenticator(){...}) 實現)
- 附件文件路徑需為服務器端絕對路徑或相對路徑可訪問位置
- Bean 與 Servlet 若不在同一包,記得
import
擴展方向
- 支持 HTML 正文:
MimeBodyPart.setContent(html, "text/html;charset=UTF-8")
- 內嵌圖片:使用
cid: 協議關聯 MimeBodyPart
- 異步發送:結合消息隊列 (JMS) 或線程池解耦發送耗時操作
- 郵件模板引擎:Velocity/FreeMarker 生成豐富內容
總結
通過 JavaMail API 封裝可復用組件,分離郵件構建邏輯與 Web 控制層,不僅實現多附件發送,更為後續功能擴展(HTML 郵件、異步發送、模板化)奠定良好架構基礎。
- 上一篇文章: 基於 Struts 框架的 MVC Web 應用開發實戰指南
- 下一篇文章: Java + MySQL + PHP 跨平台全文搜索引擎構建實戰
Copyright ©
程式碼之家 All Rights Reserved