首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 實作 POP3 郵件解碼(二):MIME 編碼原理與 Base64/QP 解碼類別

     編輯:PHP 相關知識

MIME 編碼兩大派系

  • Base64 (B):3 bytes → 4 chars,每 char 6 bits,通用性強,主旨常用
  • Quoted-Printable (Q):1 byte → "=" + 2 hex chars,適合多數 ASCII 可見字元的文本

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); // 遞迴處理多段
}

郵件本體 MIME 結構

  • multipart/alternative:純文字 + HTML 兩擇一顯示
  • multipart/mixed:郵件 + 附件
  • multipart/related:HTML + 內嵌圖片
  • 可巢狀嵌套,每層有獨立 boundary

關鍵標頭

Content-Type: multipart/mixed; boundary="xxx"
Content-Transfer-Encoding: base64

解碼流程:依 boundary 分割 → 讀取各部 Content-Type 與 Encoding → 對應解碼 → 組裝結果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved