PHP Mailparse在非ascii字符上窒息

时间:2014-10-20 21:35:51

标签: php mime email-parsing

我正在使用Mailparse在MySQL数据库中解析和存储电子邮件。电子邮件直接通过管道传输到PHP脚本。超过99%的系统电子邮件都已正确解析。但是,我注意到有些电子邮件被截断了。问题似乎是消息的标题和正文之间的unicode字符......

Delivered-To: nkafq123@gmail.com
Received: by 10.152.1.193 with SMTP id 1csp311490lao;
        Mon, 20 Oct 2014 05:33:31 -0700 (PDT)
Return-Path: <lunalono@telia.com>
Received: from vps4596.inmotionhosting.com (vps4596.inmotionhosting.com. [74.124.217.238])
        by mx.google.com with ESMTPS id fb7si7786786pab.30.2014.10.20.05.33.30
        for <nkafq123@gmail.com>
        (version=TLSv1 cipher=RC4-SHA bits=128/128);
        Mon, 20 Oct 2014 05:33:30 -0700 (PDT)
Message-ID: <14FBD481E1074C79A706F0C071746F3D@acerDator>
From: =?utf-8?Q?Annelen_geretschl=C3=A4ger?= <lunalono@telia.com>
To: "neokio" <nkafq123@gmail.com>
References: <CAEMnOreG=99=qx-ONib=g+3mCQnUHC2kgdu2uBdSav5WP303BA@mail.gmail.com>
In-Reply-To: <CAEMnOreG=99=qx-ONib=g+3mCQnUHC2kgdu2uBdSav5WP303BA@mail.gmail.com>
Subject: This message will be broken
Date: Mon, 20 Oct 2014 14:33:24 +0200
MIME-Version: 1.0
Content-Type: multipart/alternative;
    boundary="----=_NextPart_000_0018_01CFEC72.CE424470"
X-Priority: 3
X-MSMail-Priority: Normal
Importance: Normal
X-Mailer: Microsoft Windows Live Mail 14.0.8117.416
X-MimeOLE: Produced By Microsoft MimeOLE V14.0.8117.416
X-Source: 
X-Source-Args: 
X-Source-Dir: 

Det här är ett flerdelat meddelande i MIME-format.

------=_NextPart_000_0018_01CFEC72.CE424470
Content-Type: text/plain;
    charset="utf-8"
Content-Transfer-Encoding: quoted-printable

This is a test ... the above "Det här är" chunk will be cut off at "Det h", and nothing else will arrive.

------=_NextPart_000_0018_01CFEC72.CE424470

以上内容将在标题之后被裁剪,所有到达的内容都是“Det h”。不知何故,非ascii字符(ü)导致mailparse在标题或多部分包装器之外时会发生阻塞。这可能是客户端正在使用的5年历史的Microsoft Windows Live Mail版本,搞乱标题等,但这不是理由,我需要能够接收它。

我正在运行PHP 5.4.30,它在php.ini中有default_charset = "utf-8"。但我注意到phpinfo()默认有mailparse.def_charset = "us-ascii",即使php.ini中没有配置它。添加该行并将其设置为“utf8”后,phpinfo()正确显示了utf-8。但是错误仍然存​​在。我没有想法。

有关如何处理此错误的任何建议?

1 个答案:

答案 0 :(得分:3)

我在评论中提到的一个想法......这部分与消息部分有关。如果由于某种原因,解码失败,则“按原样”返回内容。您可以尝试根据$headers['transfer-encoding'];解码它或保持不变。 $email是包含标题的完整邮件来源。 $section是通过mailparse_msg_get_part(手动,示例,Google)获取的数据

$headers = mailparse_msg_get_part_data($section);
$content = '';

set_error_handler(function() use(&$content, $headers, $email){
     $start   = $headers['starting-pos-body'];
     $end     = $headers['ending-pos-body'];
     $content = substr($email, $start, $end - $start);
});

ob_start();
mailparse_msg_extract_part($section, $email);
$body = ob_get_clean();

restore_error_handler();

if (!empty($content)) $body = $content;

结果(经过一些操作,因为我只留下了我真正需要的标题)

["charset"]=>
string(5) "utf-8"
["content-charset"]=>
string(5) "utf-8"
["content-type"]=>
string(10) "text/plain"
["content"]=>
string(108) "This is a test ... the above "Det här är" chunk will be cut off at "Det h", and nothing else will arrive. "