原始郵件(RFC 5322/MIME)結構複雜:多部分、Base64/Quoted-Printable 編碼、巢狀結構、編碼宣告、附件內嵌。手工正則解析極其脆弱。PEAR Mail_mimeDecode 是成熟解決方案,現代替代品有 php-mime-mail-parser/php-mime-mail-parser。
<?php
require_once 'Mail/mimeDecode.php';
$rawEmail = file_get_contents('php://stdin'); // 或從 POP3/IMAP 獲取
$params = [
'include_bodies' => true, // 包含正文內容
'decode_bodies' => false, // 手動解碼以控制編碼
'decode_headers' => true, // 自動解碼標題
];
$decoder = new Mail_mimeDecode($rawEmail);
$structure = $decoder->decode($params);
if (PEAR::isError($structure)) {
die('郵件解析失敗:' . $structure->getMessage());
}
// 結構分析
print_r($structure);
/*
stdClass Object
(
[headers] => Array ( [subject] => ..., [from] => ..., [to] => ..., [date] => ... )
[ctype] => text/plain
[ctype_parameters] => Array ( [charset] => utf-8 )
[body] => 原始正文(未解碼)
[parts] => Array ( ... 多部分結構 ...)
)
*/
?>
<?php
class EmailParser
{
public function parse(string $rawEmail): array
{
require_once 'Mail/mimeDecode.php';
$decoder = new Mail_mimeDecode($rawEmail);
$structure = $decoder->decode([
'include_bodies' => true,
'decode_bodies' => false, // 我們自己處理編碼
'decode_headers' => true,
]);
if (PEAR::isError($structure)) {
throw new RuntimeException('Parse failed: ' . $structure->getMessage());
}
return $this->extractParts($structure);
}
private function extractParts(stdClass $part, int $depth = 0): array
{
$result = [
'headers' => $part->headers ?? [],
'content_type' => $part->ctype ?? 'text/plain',
'charset' => $part->ctype_parameters['charset'] ?? 'utf-8',
'encoding' => $part->headers['content-transfer-encoding'] ?? '7bit',
'disposition' => $part->disposition ?? 'inline',
'filename' => $part->d_parameters['filename'] ?? ($part->ctype_parameters['name'] ?? null),
'body_raw' => $part->body ?? '',
'body' => '',
'attachments' => [],
'parts' => [],
];
// 解碼正文
$result['body'] = $this->decodeBody($result['body_raw'], $result['encoding'], $result['charset']);
// 處理子部分
if (!empty($part->parts)) {
foreach ($part->parts as $subPart) {
$subResult = $this->extractParts($subPart, $depth + 1);
if ($subResult['disposition'] === 'attachment' || $subResult['filename']) {
$result['attachments'][] = $subResult;
} else {
$result['parts'][] = $subResult;
}
}
}
return $result;
}
private function decodeBody(string $body, string $encoding, string $charset): string
{
// 1. 解碼傳輸編碼
switch (strtolower($encoding)) {
case 'base64':
$body = base64_decode($body);
break;
case 'quoted-printable':
$body = quoted_printable_decode($body);
break;
case '7bit':
case '8bit':
case 'binary':
default:
break;
}
// 2. 轉換字符編碼到 UTF-8
$charset = strtoupper($charset);
if ($charset !== 'UTF-8' && function_exists('iconv')) {
$body = @iconv($charset, 'UTF-8//IGNORE', $body) ?: $body;
}
return $body;
}
/** 獲取最佳正文:優先 text/plain,其次 text/html */
public function getBestBody(array $parsed): string
{
// 遞歸查找
$finder = function (array $part) use (&$finder) {
if (str_starts_with($part['content_type'], 'text/plain')) {
return $part['body'];
}
foreach ($part['parts'] as $sub) {
if ($text = $finder($sub)) return $text;
}
return null;
};
$plain = $finder($parsed);
if ($plain) return $plain;
// 找 HTML 並轉純文本
$htmlFinder = function (array $part) use (&$htmlFinder) {
if (str_starts_with($part['content_type'], 'text/html')) {
return $part['body'];
}
foreach ($part['parts'] as $sub) {
if ($html = $htmlFinder($sub)) return $html;
}
return null;
};
$html = $htmlFinder($parsed);
return $html ? $this->htmlToText($html) : '';
}
private function htmlToText(string $html): string
{
$dom = new DOMDocument();
@$dom->loadHTML('' . $html);
$text = '';
foreach ($dom->getElementsByTagName('body')->item(0)?->childNodes ?? [] as $node) {
$text .= $this->nodeToText($node) . "\n";
}
return trim($text);
}
private function nodeToText(DOMNode $node): string
{
if ($node->nodeType === XML_TEXT_NODE) return $node->textContent;
if (in_array($node->nodeName, ['br', 'p', 'div', 'li'])) return "\n";
$text = '';
foreach ($node->childNodes as $child) $text .= $this->nodeToText($child);
return $text;
}
}
?>
<?php
// 使用 Net_POP3 (PEAR) 或 php-imap 擴展
// 這裡展示概念流程
function fetchAndParseEmails(string $host, int $port, string $user, string $pass): Generator
{
// 連接 POP3
$pop3 = new Net_POP3();
if (!$pop3->connect($host, $port)) throw new Exception('連接失敗');
if (!$pop3->login($user, $pass)) throw new Exception('登入失敗');
$list = $pop3->getListing();
$parser = new EmailParser();
foreach ($list as $msg) {
$raw = $pop3->getMsg($msg['msg_id']);
$parsed = $parser->parse($raw);
// 業務邏輯:提取關鍵資訊
yield [
'msg_id' => $msg['msg_id'],
'from' => $parsed['headers']['from'] ?? '',
'subject' => $parsed['headers']['subject'] ?? '',
'date' => $parsed['headers']['date'] ?? '',
'body_text' => $parser->getBestBody($parsed),
'attachments' => array_map(fn($a) => [
'filename' => $a['filename'],
'type' => $a['content_type'],
'size' => strlen($a['body_raw']),
'content' => $a['body_raw'], // 或存檔後返回路徑
], $parsed['attachments']),
];
// 標記刪除或保留
// $pop3->deleteMsg($msg['msg_id']);
}
$pop3->disconnect();
}
?>
<?php
// composer require php-mime-mail-parser/php-mime-mail-parser
use PhpMimeMailParser\Parser;
$parser = new Parser();
$parser->setText($rawEmail); // 或 setPath($filePath)
$to = $parser->getHeader('to');
$from = $parser->getHeader('from');
$subject = $parser->getHeader('subject');
$textBody = $parser->getMessageBody('text');
$htmlBody = $parser->getMessageBody('html');
$attachments = $parser->getAttachments();
foreach ($attachments as $attachment) {
$filename = $attachment->getFilename();
$content = $attachment->getContent();
$mimeType = $attachment->getContentType();
// file_put_contents("/tmp/$filename", $content);
}
?>
| 問題 | 原因 | 解決 |
|---|---|---|
| 中文主旨亂碼 | RFC 2047 編碼 (=?UTF-8?B?...?=) | decode_headers=true 自動處理,或手動 iconv_mime_decode() |
| 附件檔名亂碼 | 檔名編碼同主旨 | 用 mailparse_rfc822_parse_addresses() 或 Parser 內建方法 |
| 大郵件記憶體耗盡 | 一次性載入完整郵件 | 用 imap_fetchbody 分段獲取、或流式解析庫 |
| 內嵌圖片 CID 引用 | HTML 中 <img src="cid:..."> | 解析附件 Content-ID,替換 HTML 中對應 CID |
| 簽名驗證 (DKIM/SPF/DMARC) | 需檢查標頭 | 用 mailparse 或專用 DKIM 驗證庫 |
郵件解析關鍵在於:正確處理 MIME 多部分結構、傳輸編碼解碼、字符集轉換、附件識別。現代專案建議使用 php-mime-mail-parser 替代 PEAR 套件,無依賴衝突、支援 Composer、API 更直觀。若處理大量郵件,考慮 IMAP IDLE 推模式替代 POP3 輪詢,並將附件存儲到物件存儲而非資料庫。