简体   繁体   中英

PHP mail PDF attachment gets file corrupted

I'm having a big headache with this issue and I wonder if any1 could help me with this. In my tests and BCC I always see the PDF attachment correctly, but maybe 10% of the people see the PDF file as being corrupted (some people I know that they are using Outlook and I'm using Mail from 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;}

What could possibly be happening? I always see it working but few people can't open the file..

It's been a while, but finally got this problem solved. The issue is on PHP_EOL which in my case is returning \\n, while some systems the email should have \\r\\n as line break. To fix this issue just place the new $eol:

$eol = "\r\n";

The way you have set the headers seems right to me. However, couple things I noticed/do differently:

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

Take this */ away from the end

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

And for the content disposition:

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

Also, body and the attachment headers should be combined to the headers, no need to send body separately in mail():

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM