PHP邮件PDF附件导致文件损坏

时间:2013-11-14 14:17:41

标签: php pdf

我对此问题感到非常头疼,我想知道是否有任何人可以帮助我解决这个问题。在我的测试和BCC中,我总是正确地看到PDF附件,但也许有10%的人认为PDF文件已损坏(有些人我知道他们正在使用Outlook而我正在使用Mac上的Mail)。

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;}

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

2 个答案:

答案 0 :(得分:1)

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

$eol = "\r\n";

答案 1 :(得分:0)

你设置标题的方式对我来说似乎是对的。但是,我注意到/做了不同的事情:

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

从结尾拿走这个* /

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

对于内容处理:

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

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

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