尝试使用SwiftMailer通过Gmail发送电子邮件时出错

时间:2017-07-05 10:28:48

标签: php symfony swiftmailer

我正在关注Symfony 3 Documentation从我的控制器发送电子邮件,但是我收到了错误消息。我确保正确地按照上面的每一步,但没有用。

这就是我的控制器的样子:

<?php

namespace MyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction(\Swift_Mailer $mailer)
    {
        $message = (new \Swift_Message('Hello Email'))
            ->setFrom('send@example.com')
            ->setTo('my.address@gmail.com')
            ->setBody(
                $this->renderView(
                    // app/Resources/views/Emails/registration.html.twig
                    'MyBundle::Emails/registration.html.twig',
                    array('name' => 'John Doe')
                ),
                'text/html'
            );

        $mailer->send($message);

        return new Response('<html<body>Sent</body></html>');
    }
}

这是我得到的错误:

  

控制器“MyBundle \ Controller \ DefaultController :: indexAction()”要求您为“$ mailer”参数提供值。参数可以为空,并且没有提供空值,没有提供默认值,或者因为在此之后存在非可选参数。

与文档页面相比,我确信一切都是应有的,所以有人可以帮我找到这个错误的来源吗?

2 个答案:

答案 0 :(得分:3)

从构造函数中删除 $mailer (您不在服务中,您在控制器中),使用{{ 1}}发送。 (再次,你在一个控制器,你有权访问邮件服务,不需要尝试将其注入构造函数)

答案 1 :(得分:0)

我认为,您未在项目设置中启用autowiring。因此,Swift_Mailer不会自动注入。启用它或手动注入邮件服务。

在Symfony here中查看有关自动装配的更多信息。

相关问题