如何将TCPDF生成的pdf作为Swiftmailer附件发送

时间:2011-11-09 11:32:33

标签: php tcpdf swiftmailer

我已经尝试了几种解决方案,最接近(对我来说)应该是这样的:

$file = $pdf->Output('', 'E');
$message->attach(Swift_Attachment::newInstance($file, 'name.pdf', 'application/pdf'));

$pdfTCPDF的实例,$messageSwift_Message的实例。 使用上面的电子邮件正在发送正常,文件已附加,但当我尝试打开它时,我收到错误消息,文件已损坏或编码错误。

我的问题是:如何将TCPDF生成的pdf作为Swiftmailer附件发送,而不将文件保存到服务器并在发送电子邮件后将其删除Here是TCPDF输出方法文档的链接,也许有人可以看到我错过的内容。

4 个答案:

答案 0 :(得分:8)

我正在使用这样的东西,它正在发挥作用。对于PDF内容,我使用PDF库中最简单的示例之一。

[...]
$pdf_as_string = $pdf->Output('', 'S'); // $pdf is a TCPDF instance
[...]
$transport = Swift_MailTransport::newInstance(); // using php mail function
$message->setTo(array(
  "client@customdomain.com" => "Main Email",
  "client@publicdomain.com" => "Secondary Email"
));
$message->setSubject("This email is sent using Swift Mailer");
$message->setBody("You're our best client ever.");
$message->setFrom("developers@mydomain.com", "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。但以防万一是值得的。

答案 1 :(得分:4)

我在运行中附加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邮件程序版本:4.1.3

答案 2 :(得分:0)

你试过这个吗?

$file = $pdf->Output('', 'S');

我正在使用PHP中的另一个邮件后端执行此操作,这确实有效。我猜邮件后端负责编码附件,因此无需手动将其编码为base64。

答案 3 :(得分:0)

您可以使用outputmode'E'获得base64String。

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

提防:也许由于以下原因,您必须剪掉前5-6行:

  

Content-Type:应用程序/ pdf;名称=“”
  内容传输编码:base64
  内容处置:附件;
  filename =“”

     

Base64StringStartsHere ....

剪切

$base64PdfArray = explode("\r\n", $base64PdfString);
$base64 = '';
for($i = 5; $i < count($base64PdfArray); $i++) {
    $base64 .= $base64PdfArray[$i];
}

现在您将电子邮件作为base64String。
发送之前,您必须对其进行解码。

$mail->attach(new \Swift_Attachment(base64_decode($base64), 'Pdf.pdf', 'application/pdf'));