PHPMailer - send PHP generated PDF (mPDF) as attac

2019-07-17 08:12发布

问题:

I know how to generate PDF using mPDF library and send it as attachment using PHPMailer - something like this:

...
$emailAttachment = $mpdf->Output('file.pdf', 'S');
$mail = new PHPMailer();
$mail->AddStringAttachment($emailAttachment, 'file.pdf', 'base64', 'application/pdf');
...

But what if I generate PDF in separate PHP file (that should not be modified) - like this - invoice.php:

...
$mpdf = new mPDF();
$mpdf->WriteHTML($html);
$mpdf->Output();
exit;

How can I attach this dynamically created PDF file using PHPMailer? I tried this:

$mail = new PHPMailer();
...
$mail->addStringAttachment(file_get_contents('invoice.php'), 'invoice.pdf',  'base64', 'application/pdf');
$mail->send();

Email is sent with correct content but PDF attachment is corrupted and thus cannot be displayed. How to encode it correctly? I tried few other ways but file is corrupted or is not attached at all (in one case, whole email body was blank).

Thank you for your help in advance! :)

回答1:

The problem is that you're using file_get_contents incorrectly; as you've used it, it will fetch the contents of include.php, not the results of its execution. You need to expand it to a full URL in order to have it fetched that way, though I would advise not doing that. Have the script generate a PDF file and then load that, using the file output option of mpdf:

$mpdf = new mPDF();
$mpdf->WriteHTML($html);
$mpdf->Output('/path/to/files/doc.pdf', 'F');

Then run that script and attach the resulting file from PHPMailer (and delete the file afterwards):

include 'invoice.php';
$mail = new PHPMailer();
...
$mail->addAttachment('/path/to/files/doc.pdf');
$mail->send();
unlink('/path/to/files/doc.pdf');

You could skip the external file approach by using the "return a string" output mode (S) of the Output method and returning the string from the included file:

$mpdf = new mPDF();
$mpdf->WriteHTML($html);
return $mpdf->Output('doc.pdf', 'S');

and then:

$pdf = include 'invoice.php';
$mail = new PHPMailer();
...
$mail->addStringAttachment($pdf, 'doc.pdf');
$mail->send();