How to send emails in Symfony using the Mailer component?

To send emails in Symfony using the Mailer component, you can follow these steps:

  1. Install the Mailer component if you don't already have it installed. You can do this by running the following command in your terminal:
composer require symfony/mailer
  1. Configure your email settings in the config/packages/mailer.yaml file. Here's an example configuration for using the smtp transport:
framework: mailer: dsn: 'smtp://localhost'
  1. Create a service to send emails. You can create a new service in your Symfony application that uses the MailerInterface to send emails. Here's an example service that sends an email:
use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mime\Email; class EmailSender { private $mailer; public function __construct(MailerInterface $mailer) { $this->mailer = $mailer; } public function sendEmail($to, $subject, $body) { $email = (new Email()) ->from('[email protected]') ->to($to) ->subject($subject) ->html($body); $this->mailer->send($email); } }
  1. Use the service to send emails. You can now use the EmailSender service in your controller or any other part of your application to send emails. Here's an example of how you can use the service in a controller:
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class EmailController extends AbstractController { public function sendEmail(EmailSender $emailSender) { $emailSender->sendEmail('[email protected]', 'Hello', 'This is a test email'); return $this->render('email/sent.html.twig'); } }

By following these steps, you can send emails in Symfony using the Mailer component.