Home > OS >  Send pdf output as stringAttachment using PHPMailer
Send pdf output as stringAttachment using PHPMailer

Time:01-05

I am trying to attach a file using the PHPMailer's addStringAttachment method.

I generated the pdf from TCPDF using:

$b64_enc_doc = $pdf->Output($file_name, 'E');

Then inside of the script to send the email, I have

...
$mail->addStringAttachment($b64_enc_doc, $file_name)

However, the PDF attachment is corrupted when I try opening it.

I tried debugging the output of the PDF generated from TCPDF and it looks something similar to this:

Content-Type: application/pdf;
 name="file.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
 filename="file.pdf"

JVBERi0xLjcKJeLjz9MKMjEgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAxIDAgUiAvTGFz
dE1vZGlmaWVkIChEOjIwMjIwMTA0MTMwODQ2KzAwJzAwJykgL1Jlc291cmNlcyAyIDAgUiAvTWVk
aWFCb3ggWzAuMDAwMDAwIDAuMDAwMDAwIDU5NS4yNzYwMDAgODQxLjg5MDAwMF0gL0Nyb3BCb3gg
WzAuMDAwMDAwIDAuMDAwMDAwIDU5NS4yNzYwMDAgODQxLjg5MDAwMF0gL0JsZWVkQm94IFswLjAw
MDAwMCAwLjAwMDAwMCA1OTUuMjc2MDAwIDg0MS44OTAwMDBdIC9UcmltQm94IFswLjAwMDAwMCAw
LjAwMDAwMCA1OTUuMjc2MDAwIDg0MS44OTAwMDBdIC9BcnRCb3ggWzAuMDAwMDAwIDAuMDAwMDAw
IDU5NS4yNzYwMDAgODQxL...

Please I do not want to save the file to the server but send the file straight to the user's email. Please help. Thanks!

CodePudding user response:

You don't show the code you're using, but that string is a fragment of an email message, not a PDF binary PDF string as it should be.

Your code should be along the lines of (I don't remember tcpdf's syntax offhand):

//Render the PDF to a string in memory
$pdf = $tcpdf->output('S');
$mail->addStringAttachment($pdf, 'file.pdf');

PHPMailer will take care of the rest.

  •  Tags:  
  • Related