首页 > 解决方案 > Symfony 5 Mailer 未定义的方法名为“htmlTemplate”

问题描述

我希望在个人项目中使用Symfony Mailer 。这个想法是用户订阅时事通讯,然后他收到一封确认他订阅的邮件。我在我的控制器中创建了一个函数 send Mail,以便在提交表单时调用此函数。

    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');

        }

当我提交表单时,一切正常,但是当它进入我sendEmail的函数时出现以下错误:

试图调用“Symfony\Component\Mime\Email”类的名为“htmlTemplate”的未定义方法。

你知道为什么会出现这个错误吗?我不明白发生了什么。

谢谢你。

标签: phpsymfonymailer

解决方案


要使用模板,您需要使用文档中描述的 TemplatedEmail

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;
}

推荐阅读