繁体   English   中英

htmlTemplate 不适用于 symfony/mailer

[英]htmlTemplate don't work for symfony/mailer

我在 Symfony 应用程序中使用"symfony/mailer": "6.1.*" package 发送邮件。

我的 function 使用 HTML 模板,如文档

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

我不明白为什么会收到此错误:

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

在我的编辑器中, use Symfony\Bridge\Twig\Mime\TemplatedEmail; 有灰色,这意味着它没有被调用。

我的 PHP 版本是 8.1,我使用:

"symfony/twig-bundle": "6.1.*",
"twig/cssinliner-extra": "^3.4",
"twig/extra-bundle": "^3.4",
"twig/twig": "^2.12|^3.0"

谢谢。

您的“模板”文件夹中是否有一个名为“_mail”的文件夹,其中有一个名为“exception-de-base.html.twig”的文件?

根据文档( https://symfony.com/doc/current/mailer.html#html-content

要使用 Twig 定义 email 的内容,请使用 TemplatedEmail class 这个 class 扩展了正常的 Email class 但为 ZF35D70DDF2F0B7FD1849Z29F9E224D87 模板添加了一些新方法

因此,您应该能够通过以下方式解决您的错误:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM