DOMPDF - attach created PDF to email

user991830 picture user991830 · Oct 31, 2011 · Viewed 20.6k times · Source

What is the easiest way to attach a PDF to an email via DOMPDF?

The end of my script I am using (part of it) is below:

$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();    
//below to save the pdf file - not needed if emailing pdf
file_put_contents('/home/ststrave/public_html/pdf/STS_Brochure.pdf', $dompdf->output());
//below to open pdf in browser - required
$dompdf->stream("STS_Brochure_".rand(10,1000).".pdf", array("Attachment" => false));
jexit();

Just for clarification - this is being used in Joomla.

Appreciate the simplest/quickest way using standard PHP mail function.

Cheers ;-)

Answer

gearz picture gearz · Aug 17, 2012

Ok. You already accepted an answer, but for anyone else coming here, I think there is an easier way, but it's also not PHP's standard mail function, which really isn't going to work. If you can get the pear packages Mail and Mail_mime, it's really easy to send emails with attachments. You can also directly attach the DomPDF output without creating a file, like so:

$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->set_paper("letter", "portrait" );
$dompdf->render();

$output = $dompdf->output();

$mm = new Mail_mime("\n");

$mm->setTxtBody($body);
$mm->addAttachment($output,'application/pdf','output.pdf', false);

$body = $mm->get();
$headers = $mm->headers(array('From'=>$from,'Subject'=>$subject));

$mail =& Mail::factory('mail');
if($mail->send($to,$headers,$body)){
    echo "Your message has been sent.";
}