JavaMail 處理郵件接收最棘手在於 MIME 結構複雜:多層 multipart/*、巢狀 message/rfc822、編碼參雜。本文提供生產級 PraseMimeMessage 工具類,完整實現發件人/收件人/主題/日期/正文/附件/已讀狀態/回執/Message-ID 解析與附件存檔。
javax.mail.internet.MimeMessagePart 介面(MimeMessage、BodyPart 皆實作)Content-Type 分派處理邏輯public void getMailContent(Part part) throws Exception {
String ct = part.getContentType();
boolean hasName = ct.indexOf("name") != -1;
if (part.isMimeType("text/plain") && !hasName) {
bodytext.append((String) part.getContent());
} else if (part.isMimeType("text/html") && !hasName) {
bodytext.append((String) part.getContent());
} else if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
for (int i=0; i
public boolean isContainAttach(Part part) { ... } // 遞迴檢查 disposition 或 application/name
public void saveAttachMent(Part part) { ... } // 遞迴處理 multipart、message/rfc822
// 關鍵:decodeText() 處理 GB2312 等編碼檔名
// 儲存:BufferedInputStream → BufferedOutputStream 逐位元組寫入
| 方法 | 功能 |
|---|---|
| getFrom() | 發件人「姓名 <email>」格式,含 MimeUtility.decodeText |
| getMailAddress("to"/"cc"/"bcc") | 收件/抄送/密送清單 |
| getSubject() | 主題解碼 |
| getSentDate() | 日期格式化 (可自訂 pattern) |
| getReplySign() | 檢查 Disposition-Notification-To 標頭 |
| getMessageId() | Message-ID |
| isNew() | Flags.Flag.SEEN 判斷已讀/未讀 |
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("pop3");
store.connect("pop.mail.yahoo.com.cn", "username", "password");
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message[] msgs = folder.getMessages();
PraseMimeMessage pmm = null;
for (int i=0; i
MimeUtility.decodeText() 處理主題、發件人、附件檔名編碼gb2312 關鍵字判斷是否解碼\\、Linux/Unix /session.getStore("imap"))