How to attach PDF to email using Swiftmailer in Symfony2
Asked Answered
E

4

7

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);
Eternal answered 4/8, 2014 at 7:27 Comment(0)
C
11

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);
Commandment answered 2/3, 2015 at 10:14 Comment(1)
I had to write ->attach() before setBody()Misogynist
Q
6

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

$attach=getPdfFunction(); //binary
Swift_Attachment::newInstance($attach, 'document.pdf','application/pdf');
Quixotism answered 30/6, 2016 at 15:19 Comment(0)
P
5

You can add your attachement using this line:

$message->attach(\Swift_Attachment::fromPath($attach));
Pr answered 4/8, 2014 at 7:36 Comment(0)
H
2

The following code should do it:

$attachment = \Swift_Attachment::fromPath('subpath/to/attachment');
$message->attach($attachment);
Halloran answered 4/8, 2014 at 7:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.