Search code examples
symfonyswiftmailersymfony-3.4

How to fix swiftmailer configuration in Symfony 3.4 project


I am using Swiftmailer in my Symfony 3.4 project. I have programmed the following component to send mails:

class MailSender {

  private $mailer;

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


  public function sendMail($target, $subject, $content) {
      $message = (new \Swift_Message($subject))
      ->setFrom('***@gmail.com')        
      ->setTo($target)
      ->setBody($content, 'text/html');

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

}

In my services.yml I have added:

AppBundle\Service\MailSender:
    arguments:
        $mailer: '@swiftmailer.mailer'

In my parameters.yml I have added:

parameters:
  mailer_transport: smtp
  mailer_host: smtp.gmail.com
  mailer_user: ***@gmail.com
  mailer_password: ***

If I now start my server with php/bin console server:run and execute the sendMail method, unfortunately the mail doesn't get sent (although the mailer returns 1 as response). The Symfony Profiler shows me the following error log: Exception occurred while flushing email queue: Expected response code 250 but got code "530", with message "530 5.7.0 Must issue a STARTTLS command first. g185sm18205331wmf.30 - gsmtp "

What is rare is: If I construct the \Swift_Mailer object on my own in my TestCase, the mail indeed gets sent.

public function testSendMail() {
    // GIVEN
    $transport = (new \Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))
    ->setUsername('***@gmail.com')
    ->setPassword('***');
    $swiftMailer = new \Swift_Mailer($transport);
    $mailSender = new MailSender($swiftMailer);

    // WHEN
    $mailsSent = $mailSender->sendMail('***@t-online.de', 'testMail', 'The Mailsender works!');

    // THEN
    $this->assertEquals($mailsSent, 1);
}

Can anybody see why it doesn't work if I inject \Swift_Mailer as a service?


Solution

  • Did you tried this one from symfony documentation ? How to Use Gmail to Send Emails

    # app/config/parameters.yml
    parameters:
        # ...
        mailer_transport: gmail
        mailer_user:     your_gmail_username
        mailer_password: your_gmail_password
    
    # app/config/config_dev.yml
    swiftmailer:
        transport: '%mailer_transport%'
        username:  '%mailer_user%'
        password:  '%mailer_password%'
    

    Note that you should set your mailer_transport to gmail not smtp