So I designed an email template for my reset-password system. In the email templates, there are Images (logo).
I placed those images inside a folder called Email_Images
and that folder is placed inside the Public
folder!
First, I tried to link the images using Asset()
twig Function like this:
<img alt="logo 1" src="{{asset('Email_Images/1.png')}}" />
<img alt="logo 2" src="{{asset('Email_Images/2.jpg')}}" />
But none of them works. So I tried to get the image in the controller and send it to the template, like this :
$email = (new TemplatedEmail())
->from(new Address('[email protected]', 'My Subject'))
->to($user->getEmail())
->subject('Your password reset request');
$img= $email ->embed(fopen('Email_Images/1.jpg', 'r'), 'img');
$email->htmlTemplate('reset_password/email.html.twig')
->context([
'resetToken' => $resetToken,
'img' => $img,
'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
]);
In the template I did
<img alt="logo 1" src="{{ img }}" />
and I get this error :
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Symfony\Bridge\Twig\Mime\TemplatedEmail could not be converted to string").
What is the right way to add/embed an image in an Email?
Instead of getting the images in the controller and sending them to the twig page. You can do this :
First, Define a Twig namespace (called
img
for example) that points to the folder where the images are stored in. In this case, the folder is calledEmail_Images
Add those lines to
config/packages/twig.yaml
Now you can use
email.image()
twig function to embed the images inside the email.