PHP邮件PDF附件得到文件损坏


PHP mail PDF attachment gets file corrupted

我对这个问题非常头疼,我想知道是否有任何 1 可以帮助我解决这个问题。在我的测试和密件抄送中,我总是正确看到PDF附件,但可能有10%的人认为PDF文件已损坏(我知道有些人正在使用Outlook,而我使用的是Mac的邮件)。

function mail_attachment($content, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
// a random hash will be necessary to send mixed content
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// attachment name
$filename = "Invitation.pdf";
// encode data (puts attachment in proper format)
$pdfdoc = $content;
$attachment = chunk_split(base64_encode($pdfdoc));
// main header
$headers  = "From: Myself <".$from_mail.">'nBCC: me@hotmail.com".$eol;
$headers .= "MIME-Version: 1.0".$eol; 
$headers .= "Content-Type: multipart/mixed;{$eol}'tboundary='"".$separator."'"";
// no more headers after this, we start the body! //
$body = "--".$separator.$eol;
$body .= "Content-Type: text/html; charset='"utf-8'"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$body .= $message;
$body .= $eol.$eol;
// message
$body .= "Content-Type: text/plain; charset='"utf-8'"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$body .= $message.$eol;*/
// attachment
$body .= "--".$separator.$eol;
$body .= "Content-Type: application/octet-stream; name='"".$filename."'"".$eol; 
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment".$eol.$eol;
$body .= $attachment.$eol;
$body .= "--".$separator.$eol;
// send message
 $em = mail($mailto, $subject, $body, $headers);
 return $em;}

可能会发生什么?我总是看到它可以工作,但很少有人无法打开文件。

已经有一段时间了,但终于解决了这个问题。问题出在PHP_EOL在我的情况下返回',而某些系统的电子邮件应该有''r'作为换行符。要解决此问题,只需放置新$eol:

$eol = "'r'n";

您设置标题的方式对我来说似乎是正确的。但是,我注意到/做的几件事有所不同:

$headers .= "Content-Type: multipart/mixed;{$eol}'tboundary='"".$separator."'"".$eol;

把这个 */从最后拿走

$body .= $message.$eol;*/

对于内容处置:

"Content-Disposition: attachment; filename='"" . $filename . "'"".$eol;

此外,正文和附件标头应合并到标头中,无需在 mail() 中单独发送正文:

return mail($mailto, $subject, "", $headers);