我已经尝试了几种解决方案,最接近(对我来说)应该是这样的:
$file = $pdf->Output('', 'E');
$message->attach(Swift_Attachment::newInstance($file, 'name.pdf', 'application/pdf'));
$pdf
是TCPDF
的一个例子,$message
是Swift_Message
的一个例子。使用上面的电子邮件正在发送正常,文件已附加,但当我尝试打开它时,我收到错误消息,文件已损坏或编码错误。
我的问题是:如何将TCPDF生成的pdf作为Swiftmailer附件发送而不将文件保存到服务器并在发送电子邮件后将其删除。 Here是TCPDF输出方法文档的链接,也许有人可以看到我错过的东西。
我正在使用这样的东西,它正在工作。对于PDF内容,我使用的是PDF库中最简单的示例之一。
[...]
$pdf_as_string = $pdf->Output('', 'S'); // $pdf is a TCPDF instance
[...]
$transport = Swift_MailTransport::newInstance(); // using php mail function
$message->setTo(array(
"[email protected]" => "Main Email",
"[email protected]" => "Secondary Email"
));
$message->setSubject("This email is sent using Swift Mailer");
$message->setBody("You're our best client ever.");
$message->setFrom("[email protected]", "Developers United");
$attachment = Swift_Attachment::newInstance($pdf_as_string, 'my-file.pdf', 'application/pdf');
$message->attach($attachment);
[...]
也许这个答案有点晚,因为我使用的是swiftmailer v4_3_0和TCPDF v6_0_002。但以防万一是值得的。
我在飞行中附加TCPDF没有任何问题。
我调用一个函数,最终使用输出类型'S'返回PDF:
return $pdf->Output('TE_Invoice.pdf', 'S');
我使用以下方法附加文件:
$message->attach(Swift_Attachment::newInstance()
->setFilename('TE_Invoice.pdf')
->setContentType('application/pdf')
->setBody($val['file']));
其中$val['file']
是从上面返回的值。
我正在使用TCPDF版本:5.9.134和Swift Mailer版本:4.1.3
你试过这个吗?
$file = $pdf->Output('', 'S');
我在PHP
的另一个邮件后端这样做,这确实有效。我猜邮件后端负责编码附件,因此无需手动将其编码为base64。
您可以使用outputmode'E'来获取base64String。
$base64PdfString = $pdf->Output('', 'E');
注意:也许你必须削减前5-6行,因为
内容类型:application / pdf; NAME = “” 内容传输编码:base64 内容 - 处理:附件; 文件名=“”
Base64StringStartsHere ....
切
$base64PdfArray = explode("\r\n", $base64PdfString);
$base64 = '';
for($i = 5; $i < count($base64PdfArray); $i++) {
$base64 .= $base64PdfArray[$i];
}
现在您将Email作为base64String。 在发送之前你必须解码它。
$mail->attach(new \Swift_Attachment(base64_decode($base64), 'Pdf.pdf', 'application/pdf'));