How to test mailer with my gmail account in symfony

To test a mailer with your Gmail account in Symfony, you'll need to configure your Gmail account to allow less secure apps to access your account, and then set up your Symfony project to use your Gmail account for sending emails. Here's a step-by-step guide to help you achieve this:

Step 1: Allow less secure apps to access your Gmail account

  1. Go to your Google Account settings: https://myaccount.google.com
  2. Click on "Security" from the left-hand menu.
  3. Scroll down to the "Less secure app access" section.
  4. Toggle the switch to "Allow less secure apps: ON".

Step 2: Configure your Symfony project to use your Gmail account

  1. In your Symfony project, create a new file called config/parameters.yml (if it doesn't exist already).
  2. Add the following parameters to the file:
    parameters:
     mailer_transport: gmail
     mailer_host: smtp.gmail.com
     mailer_user: [email protected]
     mailer_password: your_password
     mailer_port: 587

    Replace [email protected] and your_password with your actual Gmail address and password.

Step 3: Configure the SwiftMailer bundle

  1. In your Symfony project, create a new file called config/swiftmailer.yml (if it doesn't exist already).
  2. Add the following configuration to the file:
    swiftmailer:
     transport: gmail
     host: smtp.gmail.com
     username: [email protected]
     password: your_password
     port: 587
     encryption: tls

    This configuration tells SwiftMailer to use your Gmail account for sending emails.

Step 4: Test your mailer

  1. Create a new PHP file in your Symfony project, e.g., src/Controller/TestMailerController.php.
  2. Add the following code to the file:
    
    namespace App\Controller;

use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mailer\Message;

class TestMailerController extends Controller { private $mailer;

public function __construct(MailerInterface $mailer)
{
    $this->mailer = $mailer;
}

public function sendEmail(): Response
{
    $message = (new Message())
        ->setSubject('Test email from Symfony')
        ->setFrom('[email protected]')
        ->setTo('[email protected]')
        ->setTextBody('This is a test email from Symfony');

    $this->mailer->send($message);

    return new Response('Email sent successfully!');
}

}

Replace `[email protected]` and `[email protected]` with your actual Gmail address and the recipient's email address.

**Step 5: Run the test**

1. Run the following command in your terminal:

php bin/console test:mailer


This will execute the `sendEmail` method and send an email from your Gmail account to the recipient's email address.

That's it! You should now be able to test your mailer with your Gmail account in Symfony.