How to attach PDF to email using Swiftmailer in Symfony2

Krishna Ghodke picture Krishna Ghodke · Aug 4, 2014 · Viewed 13.9k times · Source

I am sending an email using swiftmailer in symfony2, but I would like to add a specified PDF file as a file attachment to the email. How would I do that?

Here is my current code:

$message = \Swift_Message::newInstance()
    ->setSubject('Hello Email')
    ->setFrom('[email protected]')
    ->setTo('[email protected]')
    ->setBody(
        $this->renderView(
            'HelloBundle:Hello:email.txt.twig',
            array('name' => $name)
        )
    )
;
$this->get('mailer')->send($message);

Answer

user4615198 picture user4615198 · Mar 2, 2015

You have several options to attach a document to an email using swift mailer.

From the symfony doc:

    $message = Swift_Message::newInstance()
      ->setFrom('[email protected]')
      ->setTo('[email protected]')
      ->setSubject('Subject')
      ->setBody('Body')
      ->attach(Swift_Attachment::fromPath('/path/to/a/file.zip'))
    ;

$this->getMailer()->send($message);