To send emails in Symfony using the Mailer component, you can follow these steps:
composer require symfony/mailer
config/packages/mailer.yaml
file. Here's an example configuration for using the smtp
transport:framework:
mailer:
dsn: 'smtp://localhost'
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);
}
}
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.