【问题标题】:How to run the email function?如何运行电子邮件功能?
【发布时间】:2019-10-03 06:33:14
【问题描述】:
public function email($name, \Swift_Mailer $mailer)
{
    $message = (new \Swift_Message('Hello Email'))
        ->setFrom('send@example.com')
        ->setTo('my.email@example.com')
        ->setBody(
            $this->renderView(
            // templates/emails/registration.html.twig
                ':emails:task.twig',
                ['name' => $name]
            ),
            'text/html'
        )
    ;

    $mailer->send($message);

    return $this->render(':emails:task.twig');
}

我刚刚从https://symfony.com/doc/current/email.html 复制了该代码并更改了一些内容。

我想运行那个函数,但我不明白的是,第二个参数是什么?我在我的服务类中使用了这个函数。

【问题讨论】:

  • 如果你的意思是 \Swift_Mailer 它来自 DI 容器的服务。例如,您必须使用 DI 从构造函数中获取它。只需询问 \Swift_Mailer 并将实例作为第二个参数。
  • 您链接的代码看起来像是位于控制器内。在服务中,您很可能会将邮件程序添加到您的构造函数中。

标签: php symfony symfony4


【解决方案1】:
// class or controller registered in DI container
class InvoiceMailer
{
    private $mailer;

    public function __construct(\Swift_Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    private function email($name, \Swift_Mailer $mailer)
    {
        $message = (new \Swift_Message('Hello Email'))
            ->setFrom('send@example.com')
            ->setTo('my.email@example.com')
            ->setBody(
                $this->renderView(
                // templates/emails/registration.html.twig
                    ':emails:task.twig',
                    ['name' => $name]
                ),
                'text/html'
            );

         $mailer->send($message);
    }

    public function SendEmail($name)
    {
        $this->email($name, $this->mailer);
    }
}

DI using in symfony

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 2011-01-31
    • 2014-05-23
    • 2014-11-30
    • 2018-01-16
    • 1970-01-01
    相关资源
    最近更新 更多