使用mPDF和PHPmailer动态附加PDF

Pau*_*ert 5 php phpmailer mpdf

单击按钮时,我正在使用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!
    }
Run Code Online (Sandbox Code Playgroud)

我得到这个错误"无法访问文件:"然后一堆垃圾,我假设来自base64_encode.理想情况下,PDF会显示或下载并通过电子邮件发送,而无需在我的服务器上保存副本.我可以使用正在创建的临时文件,但尚未尝试过.

我已经测试了电子邮件功能,它可以在不添加附件的情况下工作,所以我知道问题在于mPDF并正确附加它.

Har*_*y B 8

使用mpdf的S选项时,文件将作为字符串返回,并忽略文件名参数.

然而,phpmailer的addAttachment函数将文件路径作为其第一个参数而不是文件作为字符串,这是您看到的错误.

您应该看看另一个名为AddStringAttachment的phpmailer函数:

AddStringAttachment($string,$filename,$encoding,$type)

http://phpmailer.worxware.com/index.php?pg=tutorial#3.2