Reputation: 73
I am trying to create a PDF stream using FPDF library and to send the pdf over e-mail using Swift Mailer. Below is my code. The mail is sent successfully and even pdf is also attached but the pdf is of zero bytes size and so could not be opened. When I download the pdf using $pdf->Output('receipt.pdf', 'D') it is successful and the content of PDF is also present. Can somebody help me to identify whether I am doing something wrong? Or do I need to set some additional fields in the message so that it will send the PDF correctly. I searched all the posts related to FPDF and swiftmailer but could not identify issue in my code.
$pdf = new FPDF();
$pdf->AddPage();
$pdf->Text(80, 30, "Dummy text");
$pdfstream = $pdf->Output('receipt.pdf', 'S');
$attachment = Swift_Attachment::newInstance($pdfstream, 'name.pdf', 'application/pdf');
$message = Swift_Message::newInstance('Dummy subject')
->setFrom(array("[email protected]" => 'XYZ'))
->setTo('[email protected]')
->setBody('Dummy body text');
$message->attach($attachment);
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($message);
EDIT 1: Below is working perfectly fine for me. Please note that I have used two external libraries SwiftMailer and FPDF so you need to do required things like imports etc. to make them work.
$pdf = new FPDF();
$pdf->AddPage();
$pdf->Text(80, 30, "Dummy text");
$data=$pdf->Output('receipt.pdf', 'S');
$message = Swift_Message::newInstance('Subject')
->setFrom(array("Geoff" => '[email protected]'))
->setTo('[email protected]')
->setBody('This is body text', 'text/html');
if(!empty($data))
{
$attachment = Swift_Attachment::newInstance($data, 'pdf_name.pdf', 'application/pdf');
$message->attach($attachment);
}
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($message);
Upvotes: 0
Views: 1712
Reputation: 20737
Try this:
$pdfstream = $pdf->Output('receipt.pdf', 'S');
$emailStream = 'Content-Type: application/pdf;'."\r\n";
$emailStream.= ' name="name.pdf"'."\r\n";
$emailStream.= 'Content-Transfer-Encoding: base64'."\r\n";
$emailStream.= 'Content-Disposition: attachment;'."\r\n";
$emailStream.= ' filename="name.pdf"'."\r\n\r\n";
$emailStream.= chunk_split(base64_encode($pdfstream), 76, "\r\n");
$attachment = Swift_Attachment::newInstance($emailStream, 'name.pdf', 'application/pdf');
Upvotes: 1