我正在为我的网络应用程序构建邮件模块。在我的当前进展阶段,我正在尝试正确获取邮件正文并对其进行解码。然而,当我遇到邮件中的国际字符时,它们无法被正确解码。
例如,我有一个原始的电子邮件正文:
--001a11c126f6bd3aa804f575bd85 Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable ss -- s Niels S=F8nderb=E6k --001a11c126f6bd3aa804f575bd85
Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable
ss
-- s
Ni= els S=F8nderb=E6k
--001a11c126f6bd3aa804f575bd85--
解码后的结果如下:
ss
-- s
Niels S�nderb�k
Niels Sønderbæk
应该是 Niels Sønderbæk
。我只在处理国际字符时遇到过这个问题。有人知道如何解决吗?我在下面包含了我的解码代码。它来自于 http://www.sitepoint.com/exploring-phps-imap-library-1/。
<?php
$imap = imap_open(...);
$uid = ...
function getBody($uid, $imap) {
$body = get_part($imap, $uid, "TEXT/HTML");
// if HTML body is empty, try getting text body
if ($body == "") {
$body = get_part($imap, $uid, "TEXT/PLAIN");
}
return $body;
}
function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false) {
if (!$structure) {
$structure = imap_fetchstructure($imap, $uid, FT_UID);
}
if ($structure) {
if ($mimetype == get_mime_type($structure)) {
if (!$partNumber) {
$partNumber = 1;
}
$text = imap_fetchbody($imap, $uid, $partNumber, FT_UID);
switch ($structure->encoding) {
case 3: return imap_base64($text);
case 4: return imap_qprint($text);
default: return imap_utf8($text);
}
}
// multipart
if ($structure->type == 1) {
foreach ($structure->parts as $index => $subStruct) {
$prefix = "";
if ($partNumber) {
$prefix = $partNumber . ".";
}
$data = get_part($imap, $uid, $mimetype, $subStruct, $prefix . ($index + 1));
if ($data) {
return $data;
}
}
}
}
return false;
}
function get_mime_type($structure) {
$primaryMimetype = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
if ($structure->subtype) {
return $primaryMimetype[(int)$structure->type] . "/" . $structure->subtype;
}
return "TEXT/PLAIN";
}
echo getBody($uid,$imap);
?>