通過 POP3/IMAP 獲取原始郵件源碼後,需解析出發件人、主題、正文(文本/HTML)、附件等結構化信息。PEAR Mail_mimeDecode 是處理 MIME 郵件的標準工具。
getMsg)。Mail_mimeDecode 並調用 decode()。<?php
function one_mail($msgId, $pop3) {
// 1. 獲取原始郵件源碼
$raw = $pop3->getMsg($msgId);
// 2. MIME 解碼
$decoder = new Mail_mimeDecode($raw);
$structure = $decoder->decode([
'include_bodies' => true,
'decode_bodies' => false, // 手動處理編碼更可控
'decode_headers' => true,
]);
// 3. 提取主體部分
$part = $structure->parts ? $structure->parts[0] : $structure;
// 4. 處理編碼
$encoding = $part->headers['content-transfer-encoding'] ?? '7bit';
$charset = $part->ctype_parameters['charset'] ?? 'ISO-8859-1';
$body = $part->body;
if (strtolower($encoding) === 'base64') {
$text = base64_decode($body);
} elseif (strtolower($encoding) === 'quoted-printable') {
$text = quoted_printable_decode($body);
} else {
$text = $body;
}
$text = iconv($charset, 'UTF-8//IGNORE', $text);
// 5. 解碼主題
$subject = $structure->headers['subject'] ?? '';
$subject = imap_mime_header_decode($subject);
$title = '';
foreach ($subject as $seg) {
$title .= ($seg->charset !== 'default') ? iconv($seg->charset, 'UTF-8', $seg->text) : $seg->text;
}
// 6. 發件人
$from = imap_mime_header_decode($structure->headers['from']);
$fromStr = '';
foreach ($from as $seg) $fromStr .= $seg->text;
preg_match('/([\w.+-]+@[\w.-]+\.\w+)/', $fromStr, $m);
$fromEmail = $m[1] ?? '';
return [
'from' => $fromEmail,
'subject' => $title,
'body' => $text,
'charset' => $charset,
];
}
<?php
// 配置
$host = 'pop.example.com'; $user = 'xxx'; $pass = 'xxx';
$pop3 = new Net_POP3();
if (!$pop3->connect($host, 110) || !$pop3->login($user, $pass)) die('連接失敗');
$list = $pop3->_cmdList();
$count = count($list);
for ($i = 0; $i < $count; $i++) {
$mail = one_mail($list[$i]['msg_id'], $pop3);
// 業務處理:入庫、自動回覆等...
// 標記刪除
$pop3->deleteMsg($list[$i]['msg_id']);
}
$pop3->disconnect();
| 問題 | 原因 | 解決 |
|---|---|---|
| 中文附件名亂碼 | RFC 2047 編碼 | 用 imap_mime_header_decode 解碼 content-disposition 中的 filename 參數 |
| HTML 正文包含 CID 圖片 | 內嵌引用 | 解析 multipart/related 結構,下載附件並替換 src="cid:..." |
| 編碼轉換失敗 | 字符集聲明錯誤或不支持 | iconv(..., 'UTF-8//IGNORE') 忽略非法字符,或用 mb_convert_encoding 自動檢測 |
| 大郵件內存溢出 | 一次性載入整郵件 | 使用 IMAP 分塊獲取(imap_fetchbody),或流式解析庫 |
PEAR 已停止維護,新項目推薦使用: