Error trying to send email through Gmail using SwiftMailer

断了今生、忘了曾经 提交于 2019-12-24 10:58:32

问题


I'm following Symfony 3 Documentation to send an email from my controller, but I'm getting an error. I made sure to follow each step from the above page correctly, but no use.

This is how my controller looks like:

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

This is the error I'm getting:

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.

Comparing to the documentation page, I'm pretty sure everything is as it should be, so can anyone please help me find the source of this error?


回答1:


Simply remove the $mailer from your constructor (you are not in a service, you are in a controller) , and use $this->get('mailer')->send($message); to send. (again, you are in a controller, you have access to the mailer service, no need to try and inject it into the constructor)




回答2:


I think, you not enable autowiring in projects settings. So, Swift_Mailer is not injected automatically. Enable it or inject mailer service manually.

See more about autowiring in Symfony here.



来源:https://stackoverflow.com/questions/44923669/error-trying-to-send-email-through-gmail-using-swiftmailer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!