Here's my code for generating a PDF on-the-fly by using MPDF and sending it as attachment. I have removed unnecessary code to make things quickly understandable.
<?php
require_once "Mail.php";
require_once "Mail/mime.php";
include 'mpdf/mpdf.php';
$server = 'my-domain-name';
$header = file_get_contents($server.'/pdf-header.php);
$html = file_get_contents($server.'/pdf-data.php);
//....Some parameters for mPDF constructor
$mpdf = new mPDF('en-x','A4','','',$marginLeft, $marginRight, $marginTop, $marginBottom, $marginHeader, $marginFooter);
// *** Set some properties of $mpdf object
$mpdf->WriteHTML($html); # Write html to pdf
$content = $mpdf->Output('', 'S'); // Saving pdf to attach to email
$content = chunk_split(base64_encode($content));
# Set $from, $to, $subject and parameters for SMTP Authentication
$bodyHTML = '<p>Some HTML Body</p>';
$bodyTXT = 'Plain Text Body for clients not supporting HTML';
$headers = array ('From' => $from, 'To' => $to,
'Reply-To' => $to, 'Subject' => $subject);
$smtpParams = array ('host' => $host, 'port' => $port,
'auth' => true, 'username' => $emailID,
'password' => $password);
$mime = new Mail_mime("
");
$mime->setTXTBody($bodyTXT);
$mime->setHTMLBody($bodyHTML);
$mime->addAttachment($content, 'application/pdf', 'report.pdf', false, 'base64', 'attachment');
# Get Mime Body
$body = $mime->get();
# Get Mime Headers
$mimeHeaders = $mime->headers($headers);
$smtp = Mail::factory('smtp', $smtpParams);
$mail = $smtp->send($to, $mimeHeaders, $body);
?>
The email is sent successfully to recipient with attachment report.pdf having file size as expected, but the attachment does not open either in any browser not in Adobo Acrobat. The encoding of report.pdf is perhaps wrong.
If I replace-
$content = $mpdf->Output('', 'S'); // Saving pdf to attach to email
$content = chunk_split(base64_encode($content));
with
$mpdf->Output();
The PDF is output to the browser perfectly, without any errors. That means I am messing-up with something in-
$mime->addAttachment($content, 'application/pdf', 'report.pdf', false, 'base64', 'attachment');
Similar problems have been discussed on StackOverflow but they are for picking up file from the storage and then email it. I have tried that also, but again, the PDF is corrupted.
Could any one please tell me what is wrong with my script?
Thanks in advance