Home » Php » php – How to attach PDF to email using Swiftmailer in Symfony2

php – How to attach PDF to email using Swiftmailer in Symfony2

Posted by: admin July 12, 2020 Leave a comment

Questions:

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);
How to&Answers:

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);

Answer:

If you want to upload a file from buffer, you can do this:

$attach=getPdfFunction(); //binary
Swift_Attachment::newInstance($attach, 'document.pdf','application/pdf');

Answer:

You can add your attachement using this line:

$message->attach(\Swift_Attachment::fromPath($attach));

Answer:

The following code should do it:

$attachment = \Swift_Attachment::fromPath('subpath/to/attachment');
$message->attach($attachment);