我正在使用 mPDF 在单击按钮时生成 PDF。我正在寻找一种使用 PHPmailer 将 PDF 添加到附件的方法。这是我尝试过的:
$mpdf = new mPDF();
$mpdf->WriteHTML($output);
$emailAttachment = $mpdf->Output('filename.pdf','S');
$emailAttachment = chunk_split(base64_encode($emailAttachment));
require_once('/inc/user_controller.php');
require_once('/inc/PHPMailer/class.phpmailer.php');
$user = new user();
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
$currentUserInfo = $user->userDetails($userId);
try {
$mail->AddAddress($currentUserInfo['emailAddress'], $currentUserInfo['firstName']);
$mail->SetFrom('name@yourdomain.com', 'First Last');
$mail->AddReplyTo('name@yourdomain.com', 'First Last');
$mail->Subject = 'Your file is attached';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML("This is a test");
$mail->AddAttachment($emailAttachment); // attachment
$mail->Send();
echo "Message Sent OK</p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
我收到此错误“无法访问文件:”,然后是一堆垃圾,我认为这些垃圾来自 base64_encode
。理想情况下,PDF 将显示或下载并通过电子邮件发送,而无需在我的服务器上保存副本。我可以接受正在创建的临时文件,但还没有尝试过。
我已经测试了电子邮件功能,它在不添加附件的情况下也能正常工作,所以我知道问题出在 mPDF 并正确附加它。
最佳答案
当您使用 mpdf 的 S 选项时,文件将作为字符串返回,文件名参数将被忽略。
但是 phpmailer 的 addAttachment 函数将文件路径作为其第一个参数而不是文件作为字符串,这就是您看到的错误。
您应该看看另一个名为 AddStringAttachment 的 phpmailer 函数:
AddStringAttachment($字符串,$文件名,$编码,$类型)
关于php - 使用 mPDF 和 PHPmailer 即时附加 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16224872/