How to send mails using gmail in symfony 4?

Member

by aubrey , in category: PHP Frameworks , 2 months ago

How to send mails using gmail in symfony 4?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 2 months ago

@aubrey 

To send emails using Gmail in Symfony 4, you need to configure the Swift Mailer library to use Gmail's SMTP server. Here are the steps:

  1. Install Swift Mailer via Composer: composer require symfony/swiftmailer-bundle
  2. Configure Swift Mailer in the config/packages/swiftmailer.yaml file: swiftmailer: transport: smtp host: smtp.gmail.com port: 465 encryption: ssl username: '[email protected]' password: 'your-password'
  3. Configure the emailer service in the config/services.yaml file: services: _defaults: autowire: true autoconfigure: true AppYourEmailerClass:
  4. Create a new class to handle email sending, for example src/YourEmailerClass.php: mailer = $mailer; } public function sendEmail() { $email = (new Email()) ->from('[email protected]') ->to('[email protected]') ->subject('Hello!') ->text('Body of the message'); $this->mailer->send($email); } }
  5. Use the emailer service wherever you need to send an email: use AppYourEmailerClass; // ... public function sendEmail(YourEmailerClass $emailer) { $emailer->sendEmail(); }


Remember to replace '[email protected]' and 'your-password' with your actual Gmail email and password in the configuration file (swiftmailer.yaml). Also, ensure that you have enabled "Less secure apps" in your Gmail account settings if you encounter any authentication issues.


With this configuration, you should be able to send emails using Gmail in Symfony 4 using the Swift Mailer library.