DOMPDF - attach created PDF to email

2019-01-14 18:03发布

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

2条回答
霸刀☆藐视天下
2楼-- · 2019-01-14 18:23

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.";
}
查看更多
乱世女痞
3楼-- · 2019-01-14 18:29

PHP's mail function has no "standard" file attachment method. It's an extremely barebones interface to the SMTP system that forces you to do ALL the work of attaching a file yourself.

I strongly suggest using PHPMailer or Swiftmailer to do the email for you - it reduces the heavy grunt work of generating your own MIME email and inserting the attachment (many many lines of code) does to maybe 5 lines total.

Note that neither of them will handle a streamed PDF from DOMPDF. You'll have to save the PDF to a temporary file and attach that,

查看更多
登录 后发表回答