Send a PDF as an emai attachment

As much as I like fPDF, I decided to use mpdf when I was creating pdfs with PHP.

Php : create pdf from html using mpdf
 
Steps
  • save the pdf as a file using the code below
  • the pdf can be saved to a file like this
  • $mpdf->Output(‘filename.pdf’,'F’); 
  • then attach the pdf file to send over email 
  • use $attachment = array(chunk_split(base64_encode($pdfdoc)));
 

<?php

  1. // download fpdf class (http://fpdf.org)
  2. require("/fpd/fpdf.php");
  3. // fpdf object
  4. $pdf = new FPDF();
  5. // generate a simple PDF (for more info, see http://fpdf.org/en/tutorial/)
  6. $pdf->AddPage();
  7. $pdf->SetFont("Arial","B",14);
  8. $pdf->Cell(40,10, "this is a pdf example");
  9. // email stuff (change data below)
  10. $to = "target@domain.com";
  11. $from = "me@domain.com";
  12. $subject = "send email with pdf attachment";
  13. $message = "

    Please see the attachment.

    ";
  14. // a random hash will be necessary to send mixed content
  15. $separator = md5(time());
  16. // carriage return type (we use a PHP end of line constant)
  17. $eol = PHP_EOL;
  18. // attachment name
  19. $filename = "example.pdf";
  20. // encode data (puts attachment in proper format)
  21. $pdfdoc = $pdf->Output("", "S");
  22. $attachment = chunk_split(base64_encode($pdfdoc));
  23. // main header (multipart mandatory)
  24. $headers = "From: ".$from.$eol;
  25. $headers .= "MIME-Version: 1.0".$eol;
  26. $headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"".$eol.$eol;
  27. $headers .= "Content-Transfer-Encoding: 7bit".$eol;
  28. $headers .= "This is a MIME encoded message.".$eol.$eol;
  29. // message
  30. $headers .= "--".$separator.$eol;
  31. $headers .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
  32. $headers .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
  33. $headers .= $message.$eol.$eol;
  34. // attachment
  35. $headers .= "--".$separator.$eol;
  36. $headers .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
  37. $headers .= "Content-Transfer-Encoding: base64".$eol;
  38. $headers .= "Content-Disposition: attachment".$eol.$eol;
  39. $headers .= $attachment.$eol.$eol;
  40. $headers .= "--".$separator."--";
  41. // send message
  42. mail($to, $subject, "", $headers);
  43. ?>

This page contains information I gathered and thought were very useful. See more notes on development.

Just to let you know, this page was last updated Thursday, Nov 21 24