PHP 內建解碼函數:base64_decode()、quoted_printable_decode()。
Subject: =?gb2312?B?xOO6w6Oh?=
// 結構:=? charset? encoding? encoded-text?=
// charset=gb2312, encoding=B(Base64), encoded-text=xOO6w6Oh
// 解碼後:"你好!"
function decode_mime($string) {
$pos = strpos($string, "=?");
if ($pos === false) return $string;
$preceding = substr($string, 0, $pos);
$search = substr($string, $pos + 2);
$d1 = strpos($search, "?");
$charset = substr($search, 0, $d1);
$search = substr($search, $d1 + 1);
$d2 = strpos($search, "?");
$encoding = substr($search, 0, $d2);
$search = substr($search, $d2 + 1);
$end = strpos($search, "?=");
$encoded_text = substr($search, 0, $end);
$rest = substr($string, $pos + 2 + strlen($charset) + 1 + strlen($encoding) + 1 + strlen($encoded_text) + 2);
switch (strtoupper($encoding)) {
case 'Q': $decoded = quoted_printable_decode($encoded_text); break;
case 'B': $decoded = base64_decode($encoded_text); break;
default: $decoded = "=?$charset?$encoding?$encoded_text?=";
}
// 處理 windows-1251 → koi8-r 轉換(可選)
if (strtolower($charset) == 'windows-1251') {
$decoded = convert_cyr_string($decoded, 'w', 'k');
}
return $preceding . $decoded . $this->decode_mime($rest); // 遞迴處理多段
}
multipart/alternative:純文字 + HTML 兩擇一顯示multipart/mixed:郵件 + 附件multipart/related:HTML + 內嵌圖片boundaryContent-Type: multipart/mixed; boundary="xxx"
Content-Transfer-Encoding: base64
解碼流程:依 boundary 分割 → 讀取各部 Content-Type 與 Encoding → 對應解碼 → 組裝結果。