I'm using the "symfony/mailer": "6.1.*"
package in a Symfony application to send the mails.
My function use HTML template like the doc:
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
public function index(MailerInterface $mailer,Exception $exception): Response
{
$email = (new Email())
->from('from@example.com')
->to('to@example.com')
->subject('Symfony Mailer!')
->htmlTemplate('_mail/exception-de-base.html.twig')
->context([
'code' => $exception->getCode(),
'heureDate' => (new DateTime())->format('d/m/Y H:i:s'),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'message' => $exception->getMessage(),
])
;
$mailer->send($email);
}
I don't understand why I get this error:
Attempted to call an undefined method named "htmlTemplate" of class "Symfony\Component\Mime\Email".
In my editor, the use Symfony\Bridge\Twig\Mime\TemplatedEmail;
has the gray color, that means it is not called.
My PHP version is 8.1 and I use:
"symfony/twig-bundle": "6.1.*",
"twig/cssinliner-extra": "^3.4",
"twig/extra-bundle": "^3.4",
"twig/twig": "^2.12|^3.0"
Thanks.
According to the documentation (https://symfony.com/doc/current/mailer.html#html-content)
To define the contents of your email with Twig, use the TemplatedEmail class. This class extends the normal Email class but adds some new methods for Twig templates
So you should be able to solve your error with:
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
$email = (new TemplatedEmail())
->from('fabien@example.com')
->to(new Address('ryan@example.com'))
->subject('Thanks for signing up!')
// path of the Twig template to render
->htmlTemplate('emails/signup.html.twig')
// pass variables (name => value) to the template
->context([
'expiration_date' => new \DateTime('+7 days'),
'username' => 'foo',
])
;