1

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.

mbyou
  • 104
  • 1
  • 7
  • 2
    Perhaps `$email = (new TemplatedEmail())` – Cerad Jul 23 '22 at 15:01
  • @Perhaps Thenk you – mbyou Jul 27 '22 at 13:43
  • 2
    This is the second time you thanked me which is nice but be aware that stackoverflow frowns on simple thank you comments. Which is probably why your first one got deleted. I might add that someone did take the time to write a full answer. Perhaps you could extend your gratitude to them as well by accepting their answer. – Cerad Jul 27 '22 at 14:13

1 Answers1

2

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',
    ])
;
Monnomcjo
  • 715
  • 1
  • 4
  • 14