sajad torkamani

In a nutshell

Symfony’s Mailer and Mime components give you a powerful way to create and send emails with support for:

  • Multi-part messages
  • Twig integration
  • CSS inlining
  • File attachments
  • High availability mailers to try with back-up transports in case others fail.
  • Load balancing to distribute mailing between multiple transports.

Setup

Install

composer require symfony/mailer

Setup transport (e.g., SMTP)

Your emails are delivered via a “transport”. Configure your transport at config/packages/mailer.yaml:

framework:
    mailer:
        dsn: '%env(MAILER_DSN)%'

Symfony’s Mailer also supports several 3rd party providers like SendGrid or Mailgun and provides Flex recipes to ease the installation and setup. View the docs for more info.

Create and send message

// src/Controller/MailerController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;

class MailerController extends AbstractController
{
    #[Route('/email')]
    public function sendEmail(MailerInterface $mailer): Response
    {
        $email = (new Email())
            ->from('hello@example.com')
            ->to('you@example.com')
            //->cc('cc@example.com')
            //->bcc('bcc@example.com')
            //->replyTo('fabien@example.com')
            //->priority(Email::PRIORITY_HIGH)
            ->subject('Time for Symfony Mailer!')
            ->text('Sending emails is fun again!')
            ->html('<p>See Twig integration for better HTML integration!</p>');

        $mailer->send($email);

        // ...
    }
}

This will send the message via the transport you configured. If you configured the transport to send emails asynchronously, the message won’t be sent until a worker consumes it.

Other notes

  • When using SMTP, the default timeout for sending a message before throwing an exception is the value defined in the default_socket_timeout PHP.ini option.
  • Mailer also dispatches a Symfony event that you can use to modify emails as needed.

Sources

Tagged: Symfony

Leave a comment

Your email address will not be published. Required fields are marked *