我正在尝试使用FPDF库创建PDF流,并使用Swift Mailer通过电子邮件发送pdf。以下是我的代码。邮件发送成功,甚至附加了pdf,但pdf的字节大小为零,因此无法打开。当我使用$ pdf->输出('receipt.pdf','D')下载pdf时,它是成功的,并且PDF的内容也存在。有人可以帮我确定我是否做错了什么?或者我是否需要在消息中设置一些其他字段,以便正确发送PDF。我搜索了与FPDF和swiftmailer相关的所有帖子,但无法识别我的代码中的问题。
$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("abc@xyz.com" => 'XYZ'))
->setTo('pqr@abc.com')
->setBody('Dummy body text');
$message->attach($attachment);
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($message);
编辑1: 以下对我来说非常好。请注意,我使用了两个外部库SwiftMailer和FPDF,因此您需要执行诸如导入等所需的操作才能使它们正常工作。
$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" => 'abc@xyz.com'))
->setTo('xyz@abc.com')
->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);
答案 0 :(得分:1)
试试这个:
$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');