PHP Symfony 2.8 Swiftmailer bundle 2.5,通过代码创建带有 PDF 附件的邮件

PHP Symfony 2.8 Swiftmailer bundle 2.5, create message with PDF attachment from code

我正在尝试使用 Symfony 2.8 和 SwiftMailer Bundle 2.5 创建一条 SwiftMailer 消息,我将带有简单 HTML 消息的 PDF 发送到一个地址。我可以发送电子邮件,但是所有示例代码都使用了诸如 addPart() 和 attach() 之类的方法,这些方法不存在于 Swift_Message 给出的方法列表中,而且我找不到任何使用其他方法的示例.

我从呈现的 Twig 模板创建一个 PDF,然后创建一条消息将其附加到

$pdf = $this->get('knp_snappy.pdf')->getOutputFromHtml($response);

$message = \Swift_Message::newInstance()
                ->setSubject('Hello Email')
                ->setFrom('send@example.com')
                ->setTo('recipient@example.com')
                ->setBody(
                    $this->renderView(
                    // app/Resources/views/Emails/registration.html.twig
                        'Emails/registration.html.twig',
                        array('name' => "test")
                    ),
                    'text/html'
                );

附件: $attachment = \Swift_Attachment::newInstance($pdf, $pdf_name, 'application/pdf');

两者都

$message->addPart($attachment, $contentType = "application/pdf", $charset = null);

$message->attach(\Swift_Attachment::fromPath('/path/to/image.jpg')->setFilename('myfilename.jpg'));

方法根本不存在。

奇怪的是,突出显示的消息显示

Method 'attach' not found in class \Swift_Mime_MimePart less...
Referenced method is not found in subject class.

但鉴于 Swift_Mime_MimePart class 在class 层次结构,从不在代码中直接调用或引用。

查看调用的所有单个方法,它们都以 return $this 结尾,其中 return 是对象的实例,作为方法位于最低层级的泛型类型。

由于 PHP 中没有泛型加载,setBody returns Swift_Mime_MimePart 而其他方法 return Swift_Mime_SimpleMessage,而不是 ? extends Swift_Mime_MimePart? extends Swift_Mime_SimpleMessage。因为该示例将消息设置在同一链中并且 setBody 是最后调用的方法,所以 $message 现在是 Swift_Mime_MimePart 而不是 Swift_Message,其中 attach()方法和其他位于。

因此解决方案非常简单;将调用放在不同的行上,以便 $message 保持 Swift_Message

$message = \Swift_Message::newInstance();
$message->setSubject('Hello Email')
$message->setFrom('send@example.com')
$message->setTo('recipient@example.com')
$message->setBody(
                    $this->renderView(
                    // app/Resources/views/Emails/registration.html.twig
                        'Emails/registration.html.twig',
                        array('name' => "test")
                    ),
                    'text/html'
                );
$attachment = \Swift_Attachment::newInstance($pdf, $pdf_name, 'application/pdf');
$message->attach($attachment);