PHP adding a pdf to email

2019-09-17 18:36发布

I have successful created a pdf file on a website. What I would like to do is send that pdf as an attachment in an email. So far it appears that I have successfully attached the file however when attempting to open the attachment acrobat reader give me this error message:

Acrobat could not open 'example2.pdf' because it is either not a supported type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded)

I think this error message has hit the nail on the head, below is my code does anyone know what needs to be changed? Thanks advance :)

$to = "me@domain"; 
$from = "me@domain.com"; 
$subject = "send email with pdf attachment"; 
$message = "<p>Please see the attachment.</p>";
// 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 = "example.pdf";
// encode data (puts attachment in proper format)
$attachment = chunk_split(base64_encode("/include/pdf.php?reportid=849980"));
// main header (multipart mandatory)
$headers  = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol; 
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"".$eol.$eol; 
$headers .= "Content-Transfer-Encoding: 7bit".$eol;
$headers .= "This is a MIME encoded message.".$eol.$eol;
// message
$headers .= "--".$separator.$eol;
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$headers .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$headers .= $message.$eol.$eol;
// attachment
$headers .= "--".$separator.$eol;
$headers .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol; 
$headers .= "Content-Transfer-Encoding: base64".$eol;
$headers .= "Content-Disposition: attachment".$eol.$eol;
$headers .= $attachment.$eol.$eol;
$headers .= "--".$separator."--";
// send message
mail($to, $subject, "", $headers);

1条回答
来,给爷笑一个
2楼-- · 2019-09-17 19:18
$filename = "example.pdf";
// encode data (puts attachment in proper format)
$attachment = chunk_split(base64_encode("/include/pdf.php?reportid=849980"));

looks to be your problem. Your attachment does appear to be the pdf, but instead a php page... also you need to binary (rb) read-in the file contents of the pdf, something like:

$filename = 'example.pdf';  
$fileloc = '/path/to/pdf/'.$filename;   

$filehandle = fopen($fileloc, 'rb');
$data = fread($filehandle, filesize($fileloc));
fclose($filehandle);                

$attachment = chunk_split(base64_encode($data)); 
查看更多
登录 后发表回答