Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching a PDF on the fly using mPDF and PHPmailer

I'm using mPDF to generate PDF's when a button is clicked. I am looking for a way to add the PDF to an attachment using PHPmailer. Here is what I've tried:

$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('[email protected]', 'First Last');
      $mail->AddReplyTo('[email protected]', '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!
    }

I get this error "Could not access file:" then a bunch of junk, which I assume comes from the base64_encode. Ideally, the PDF would display or download and be emailed as well without saving a copy on my server. I can live with a temp file being created, but haven't tried that yet.

I've tested the email functionality and it works without adding an attachment, so I know the issues is with mPDF and attaching it properly.

like image 982
Paul Dessert Avatar asked Apr 25 '13 21:04

Paul Dessert


1 Answers

When you use mpdf's S option the file is returned as a string and the file name parameter is ignored.

However phpmailer's addAttachment function takes a file path as its first parameter not a file as a string, hense the error you are seeing.

You should take a look at an alternative phpmailer function called AddStringAttachment:

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

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

like image 190
Harry B Avatar answered Sep 21 '22 03:09

Harry B