Search code examples
phpemailpdfencode

PHP adding a pdf to email


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 = "[email protected]"; 
$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);

Solution

  • $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));