我试图将收到的邮件传输到PHP脚本中,以便将它们存储在数据库和其他东西中。我正在使用(须登记)类,尽管我不认为这很重要。
我对电子邮件的主题有问题。当标题是英文的时候,它工作得很好,但是如果主题使用非拉丁字符,我会得到一些类似的内容。
=?UTF-8?B?2KLYstmF2KfbjNi0?=一个像یکدوسه这样的标题
我对这个主题的解读如下:
$subject = str_replace('=?UTF-8?B?' , '' , $subject);
$subject = str_replace('?=' , '' , $subject);
$subject = base64_decode($subject); 它可以很好地工作,与类似10-15个字符的短主题,但与较长的标题,我得到一半的原始标题与类似的���在结尾。
如果标题更长,比如30个字符,我什么也得不到。我做得对吗?
发布于 2012-12-04 00:48:20
尽管这已经有将近一年的历史了,但我发现了这个问题,并面临着类似的问题。
我不知道你为什么会得到奇怪的字符,但也许你想把它们显示在你的字符集不受支持的地方。
下面是我编写的一些代码,它应该处理除字符集转换之外的所有内容,这是许多库处理得更好的一个大问题。(例如,PHP的MB库 )
class mail {
/**
* If you change one of these, please check the other for fixes as well
*
* @const Pattern to match RFC 2047 charset encodings in mail headers
*/
const rfc2047header = '/=\?([^ ?]+)\?([BQbq])\?([^ ?]+)\?=/';
const rfc2047header_spaces = '/(=\?[^ ?]+\?[BQbq]\?[^ ?]+\?=)\s+(=\?[^ ?]+\?[BQbq]\?[^ ?]+\?=)/';
/**
* http://www.rfc-archive.org/getrfc.php?rfc=2047
*
* =?<charset>?<encoding>?<data>?=
*
* @param string $header
*/
public static function is_encoded_header($header) {
// e.g. =?utf-8?q?Re=3a=20Support=3a=204D09EE9A=20=2d=20Re=3a=20Support=3a=204D078032=20=2d=20Wordpress=20Plugin?=
// e.g. =?utf-8?q?Wordpress=20Plugin?=
return preg_match(self::rfc2047header, $header) !== 0;
}
public static function header_charsets($header) {
$matches = null;
if (!preg_match_all(self::rfc2047header, $header, $matches, PREG_PATTERN_ORDER)) {
return array();
}
return array_map('strtoupper', $matches[1]);
}
public static function decode_header($header) {
$matches = null;
/* Repair instances where two encodings are together and separated by a space (strip the spaces) */
$header = preg_replace(self::rfc2047header_spaces, "$1$2", $header);
/* Now see if any encodings exist and match them */
if (!preg_match_all(self::rfc2047header, $header, $matches, PREG_SET_ORDER)) {
return $header;
}
foreach ($matches as $header_match) {
list($match, $charset, $encoding, $data) = $header_match;
$encoding = strtoupper($encoding);
switch ($encoding) {
case 'B':
$data = base64_decode($data);
break;
case 'Q':
$data = quoted_printable_decode(str_replace("_", " ", $data));
break;
default:
throw new Exception("preg_match_all is busted: didn't find B or Q in encoding $header");
}
// This part needs to handle every charset
switch (strtoupper($charset)) {
case "UTF-8":
break;
default:
/* Here's where you should handle other character sets! */
throw new Exception("Unknown charset in header - time to write some code.");
}
$header = str_replace($match, $data, $header);
}
return $header;
}
}当运行脚本并使用UTF-8在浏览器中显示时,结果是:
آزمایش
你会这样运行它:
$decoded = mail::decode_header("=?UTF-8?B?2KLYstmF2KfbjNi0?=");发布于 2014-04-29 11:46:33
您可以使用mb_decode_mimeheader()函数来解码字符串。
发布于 2016-02-25 10:14:16
使用php本机函数
<?php
mb_decode_mimeheader($text);
?>这个函数可以处理utf8以及iso-8859-1字符串.我已经测试过了。
https://stackoverflow.com/questions/8626786
复制相似问题