Search code examples
phpsymfonymailer

Symfony 5 Mailer undefined method named "htmlTemplate"


I'm looking to use Symfony Mailer Inside a personal project. The idea is the user subscribe to a newsletter, then he received a mail that confirm he subscribe. I've made a function send Mail inside my controller to call this function when the form is submit.

    function sendEmail(MailerInterface $mailer, $useremail)
    {
        $email = (new Email())
            ->from('mail@mail.exemple')
            ->to($useremail)
            ->subject('Great !')
            ->htmlTemplate('emails/signup.html.twig');

        $mailer->send($email);
        return $email;
    }

     /**
     * @Route("/", name="homepage")
     */
    public function index(Request $request, MailerInterface $mailer)
    {
        $mailing = new Mailing();
        $form = $this->createForm(MailingType::class, $mailing);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            $task = $form->getData();


            $this->sendEmail($mailer , $request->request->get('mailing')['email']);

            return $this->redirectToRoute('homepage');

        }

When I submit the form, Everything is okay but when it come inside my sendEmail function the following error appear :

Attempted to call an undefined method named "htmlTemplate" of class "Symfony\Component\Mime\Email".

Do you have any idea about why this error appear ? I'don't understand what's happening.

THank you.


Solution

  • To use a template, you need to use a TemplatedEmail as described in the docs

    use Symfony\Bridge\Twig\Mime\TemplatedEmail;
    
    function sendEmail(MailerInterface $mailer, $useremail)
    {
      $email = (new TemplatedEmail())
        ->from('mail@mail.exemple')
        ->to($useremail)
        ->subject('Great !')
        ->htmlTemplate('emails/signup.html.twig');
    
      $mailer->send($email);
      return $email;
    }