简体   繁体   中英

Error trying to send email through Gmail using SwiftMailer

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?

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)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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