0

【遇到的问题】

尝试使用 PHP 的 base64_decode 函数来解码使用 Base64 编码的邮件内容,可是发现有些邮件会返回 false 。据我测试,似乎将含有非 Base64 编码的部分删除后就能正常解码了,可是根据文档说明——

string base64_decode ( string $data [, bool $strict = false ] )

当设置 strict 为 TRUE 时,一旦输入的数据超出了 base64 字母表,将返回 FALSE。 否则会静默丢弃无效的字符吗?

我要解码含非编码内容的邮件又该怎么操作?

【相关代码】

●要解码的邮件内容示例。只有删掉头尾的那些“------=_Part_…”才能解码成功,否则返回 false 。

<?php
  $str='------=_Part_52_1608986047.1312859369078 Content-Type: multipart/alternative; boundary="----=_Part_53_1114408905.1312859369078" ------=_Part_53_1114408905.1312859369078 Content-Type: text/plain; charset="gb18030" Content-Transfer-Encoding: base64 1eLKx9K7t+JIVE1MuPHKvdPKvP6jrMfrx9C7u7W9SFRNTMrTzbw ------=_Part_53_1114408905.1312859369078 Content-Type: text/html;charset=UTF-8 Content-Transfer-Encoding: base64 PG1ldGEgY2hhcnNldD0iVVRGLTgiIC8+PHRhYmxlIGFsaWduPSJjZW50ZXIiIHN0eWxlPSJmb250 LWZhbWlseTpNaWNyb3NvZnQgWWFIZWksU2ltc3VuO3dpZHRoOjc1MHB4O3RhYmxlLWxheW91dDpm aXhlZDsiICBiZ2NvbG9yPSIjZmZmZmZmIiBjZWxscGFkZGluZz0iMCIgY2VsbHNwYWNpbmc9IjAi Pjx0Ym9keT48dHI+PHRkIHN0eWxlPSJkaXNwbGF5Om5vbmU7Ij7lhaXpl6gyOTwvdGQ+PC90cj4g PHRyPjx0ZD48dGFibGUgc3R5bGU9IndpZHRoOjc1MHB4OyIgYm9yZGVyPSIwIiBjZWxscGFkZGlu Zz0iMCIgY2VsbHNwYWNpbmc9IjAiPjx0cj48dGQgc3R5bGU9IndpZHRoOjc1MHB4O2hlaWdodDox MDBweDtmb250LWZhbWlseTpNaWNyb3NvZnQgWWFIZWksU2ltc3VuO2JhY2tncm91bmQ6IzE3MjAz ZjsiPjxpbWc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Plho3mlLbliLDor6Xkuqflk4HnmoTmjqjo jZDpgq7ku7bvvIzor7fngrnlh7sgPGEgc3R5bGU9ImZvbnQtc2l6ZToxMHB4IiBocmVmPSJodHRw Oi8vZG0ubWFpbC4xNjMuY29tL2Fub255bW91cy9hZHN1YnNjcmliZS91bnN1YnNjcmliZT9kZXBJ ZD0xJnByb0lkPTEwNjAwMyZtaXRJZD02MDU2NTM4OCZzZWM9QjJkTkFCeW10WWg3UzlZa0Y2QWpl R1RqNzRqZWRTMGwiIGhpZGVmb2N1cz0idHJ1ZSI+6L+Z6YeM6YCA6K6iPC9hPjwvZGl2Pg0KPC9k aXY+DQo------=_Part_53_1114408905.1312859369078-- ------=_Part_52_1608986047.1312859369078--
';

  $text=base64_decode($str);
  var_dump($text);
  echo $text;
?>

【进行过的尝试】

改用 imap_base64 也没有成功。

【测试环境】

●XAMPP
操作系统:Windows 10 家庭中文版 1803
Apache版本:2.4.16 (Win32)
PHP版本:5.6.12

2018-12-03 提问

查看全部 3 个回答

0

关于 base64_decode 解码返回 false 的问题,上官元恒 已经回答清楚了。

关于邮件的解码问题,我自己通过研读 PHP 手册中 imap_fetchstructure 与 imap_fetchbody 下的用户注释与不断测试解决了。

总的来说就是,电邮分为 simple 和 multipart。simple 的邮件使用 imap_fetchstructure 获取的 encoding 就是邮件实际使用的编码;而 multipart 的邮件可能包含多个 parts,而每个 part 里可能又包含多个 parts,每部分 part 的 type 和 encoding 可能都不一样,因此需要通过循环逐个进行解析。每个 part 都可以根据对应的 encoding 进行解码,这样就不会遇到需要解码的内容中含有非编码内容的问题了!

具体可结合参考——

  1. PHP 手册中 imap_fetchstructure 说明下用户“david at hundsness dot com”的注释:PHP:imap_fetchstructure - Manual
  2. PHP 手册中 imap_fetchbody 说明下用户“atamido at gmail dot remove dot com”的注释:PHP:imap_fetchbody - Manual

推荐答案

1

已采纳

不是base64怎么解码。。。

你可能感兴趣的

推广链接