How to send mails using gmail in symfony 4?

2.7k Views Asked by At

enter image description here I am using symfony 4.2,

In .env file:

MAILER_URL=gmail://saurabhofficial:qwerty@localhost?encryption=tls&auth_mode=oauth

swiftmailer.yaml

swiftmailer:
url: '%env(MAILER_URL)%'
spool: { type: 'memory' }

Service:

namespace App\Service;

use App\Service\WelcomeMessage;

class WelcomeMail
{
    private $welcomeMsgGenerator;
    private $mailer;

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

    public function createMail()
    {
        $content = $this->msg->getWelcomeMessage();

        $message = (new \Swift_Message('Saurabh!'))
            ->setFrom('[email protected]')
            ->setTo('******@gmail.com')
            ->addPart(
                'Message'.$content
            );


        return $this->mailer->send($message) > 0;
    }
}

Controller:

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;

use App\Service\WelcomeMail;
use Symfony\Component\HttpFoundation\Response;

class ServicesController extends Controller
{
    /**
     * @Route("/services", name="services")
     */
    public function sendMailUsingServices(WelcomeMail $welcomeMail)
    {
        if($welcomeMail->createMail()){
            $show = 'Check your Mail';
        }
        else{
            die('Not working');
        }

        return $this->render('services/index.html.twig', [
            'show' => $show,
        ]);
    }
}

if($welcomeMail->createMail()){ $show = 'Check your Mail'; }
Above code gives me 'true', but mail mail is not sent/received. What am I doing wrong? Is any another way to implement it in SYMFONY 4?

Update

services.yaml

# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    locale: 'en'

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
        public: false       # Allows optimizing the container by removing unused services; this also means
                            # fetching services directly from the container via $container->get() won't work.
                            # The best practice is to be explicit about your dependencies anyway.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones

config/packages/dev/swiftmailer.yaml

swiftmailer:
    # send all emails to a specific address
    #delivery_addresses: ['[email protected]']
2

There are 2 best solutions below

14
On

Try to use your full e-mail address instead of just the username (ie, saurabhofficial).

Also, please check e-mail delivery is not disabled in config/packages/dev/swiftmailer.yaml (I assume you are using dev environment).

0
On

This is my solution .

Steps:

  • connection SMTP with google

  • define as a service

  • And to use it I call it from the controller

It works perfect on symfony 4: https://stackoverflow.com/a/55542824/2400373