PHPMailer-发送PHP生成的PDF(mPDF)作为附件 [英] PHPMailer - send PHP generated PDF (mPDF) as attachment

查看:307
本文介绍了PHPMailer-发送PHP生成的PDF(mPDF)作为附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用mPDF库生成PDF并使用PHPMailer将其作为附件发送-这样:

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

但是,如果我在单独的PHP文件中生成PDF(不应修改),该怎么办-像这样-invoice.php:

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;

如何使用PHPMailer附加此动态创建的PDF文件? 我试过了:

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

电子邮件发送的内容正确,但是PDF附件已损坏,因此无法显示.如何正确编码?我尝试了其他几种方法,但是文件已损坏或根本没有连接(在一种情况下,整个电子邮件正文为空白).

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

谢谢您的帮助! :)

推荐答案

问题是您错误地使用了file_get_contents.如您所用,它将获取include.php的内容,而不是其执行结果.您需要将其扩展为完整的URL,以便以这种方式获取它,尽管我建议您不要这样做.让脚本生成PDF文件,然后使用 mpdf的文件输出选项加载该文件:

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

然后运行该脚本,并从PHPMailer附加结果文件(然后删除该文件):

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

您可以通过使用Output方法的返回字符串"输出模式(S)并从包含的文件中return删除字符串来跳过外部文件方法:

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

然后:

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

这篇关于PHPMailer-发送PHP生成的PDF(mPDF)作为附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆