Search code examples
symfony4swiftmailer

How to add an image in an email with swiftmailer?


I'm trying to have an image in the email. I use Symfony 4 and SwiftMailer. I read the documentation, the forum but it doesn't work. So I tried:

 $message = (new \Swift_Message('Title of the email'))
                        ->setFrom('myemailadress@xxxxxx.com')
                        ->setTo($data['email']);

                    $headers = $message->getHeaders();

                    $attachment = \Swift_Attachment::fromPath('assets/img/logo.png');

                    $headers = $attachment->getHeaders();
 $message->setBody(
                        $this->renderView(
                            'resetemail.html.twig',
                            [ 'resetPassword' => $resetPassword], $headers
                        ),
                        'text/html'
                    );
$mailer->send($message);
                    return $this->redirectToRoute("requestMail");

For the Twig, I did:

<img id="customHeaderImage" align="top" label="Image" src="headers" alt="the title of the logo" class="w640" border="0" style="display: inline">

I also tried to replace the headers'part by: $img = $message->embed(Swift_Image::fromPath('assets/img/logo.png'));

But I just have : enter image description here

If you have a solution, I would love to read it.

Thanks.


Solution

  • This is the solution that I found :

    $message = (new \Swift_Message('Title of the email'))
                            ->setFrom('myemailadress@xxxxxx.com')
                            ->setTo($data['email'])
                            ->attach(\Swift_Attachment::fromPath('build/logo.png')->setFilename('logo.png'));
    

    So I attach the image to my message and I give it a name.

    In my Twig I just put name in the src of the img.