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

Error trying to send email through Gmail using 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>');
    }
}

这是我遇到的错误:

Controller "MyBundle\Controller\DefaultController::indexAction()" requires that you provide a value for the "$mailer" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.

与文档页面相比,我很确定一切都应该如此,所以任何人都可以帮我找到这个错误的根源吗?

我想,您没有在项目设置中启用 autowiring。因此,Swift_Mailer 不会自动注入。启用它或手动注入邮件程序服务。

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

只需从您的构造函数中删除 $mailer(您不在服务中,而是在控制器中) , 并且 使用 $this->get('mailer')->send($message); 发送 。 (同样,您在控制器中,您可以访问邮件服务,无需尝试将其注入构造函数)