Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 62 ยท Events, Messaging and Console

Mailer and Notifier

Send email with Symfony Mailer (DSNs, Email, TemplatedEmail, async via Messenger) and multi-channel alerts with Notifier, with runnable stand-ins for both.

Almost every application has to talk to users outside the browser: a welcome email, a password reset link, an invoice, a "someone logged in from a new device" alert. Symfony covers this with two components. Mailer sends email through a transport you configure with one string. Notifier goes further: one notification can travel by email, SMS, chat message or browser push, depending on how important it is.

Sending real email needs an SMTP server or an email service, so the real code in this lesson is read-only. Each part also has a plain-PHP stand-in that runs on the page, so you can see the flow: building a message, choosing a transport, failing over, queueing, and routing alerts by importance. This lesson relies on Messenger for the asynchronous parts and on configuration and environments for the DSN.

Mailer in five minutes

Install the component with composer require symfony/mailer. The whole connection is described by one environment variable, the DSN:

DOTENV
# .env (real Symfony, read-only)
MAILER_DSN=smtp://localhost:1025

The scheme picks the transport. A few you will meet:

DSN Meaning
smtp://user:[email protected]:587 Any SMTP server
sendmail://default The local sendmail binary
null://null Accept and discard everything (handy in tests)
smtp://localhost:1025 A local catcher such as Mailpit, which shows mail in a web page instead of delivering it
postmark+api://ID@default, ses+api://... Provider bridges, each installed as its own package (for example symfony/postmark-mailer)
failover(a b) and roundrobin(a b) Combine several transports for reliability or load sharing

Keep real credentials out of .env: put them in .env.local or the secrets vault.

Building and sending an email

PHP
// src/Controller/SignupController.php (real Symfony, read-only)
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;

#[Route('/signup', methods: ['POST'])]
public function signup(MailerInterface $mailer): Response
{
    $email = (new Email())
        ->from(new Address('[email protected]', 'Example Shop'))
        ->to('[email protected]')
        ->subject('Welcome!')
        ->text('Thanks for signing up.')
        ->html('<p>Thanks for signing up.</p>');

    try {
        $mailer->send($email);
    } catch (TransportExceptionInterface $e) {
        // The server was unreachable or refused the message.
    }

    return $this->redirectToRoute('home');
}

Email is a fluent builder from the Mime component: to(), cc(), bcc(), replyTo(), attachFromPath() and embedFromPath() for files. Always provide a plain-text part next to the HTML part; spam filters and some mail apps prefer it.

You can avoid repeating the sender by setting a default envelope in config/packages/mailer.yaml (framework.mailer.envelope.sender). In development you can redirect all mail to one address with framework.mailer.envelope.recipients.

Templated email with Twig

Writing HTML in PHP strings does not scale. TemplatedEmail renders a Twig template for you:

PHP
// real Symfony, read-only
use Symfony\Bridge\Twig\Mime\TemplatedEmail;

$email = (new TemplatedEmail())
    ->from('[email protected]')
    ->to($user->getEmail())
    ->subject('Welcome, ' . $user->getName())
    ->htmlTemplate('emails/welcome.html.twig')
    ->textTemplate('emails/welcome.txt.twig')
    ->context(['user' => $user, 'loginUrl' => $loginUrl]);

$mailer->send($email);
TWIG
{# templates/emails/welcome.html.twig (real Symfony, read-only) #}
<h1>Welcome, {{ user.name }}!</h1>
<p><a href="{{ loginUrl }}">Open your account</a></p>
<img src="{{ email.image('@images/logo.png') }}" alt="Logo">

Inside the template, the email variable exposes helpers such as email.image(), which embeds a file as an attachment referenced by the HTML (many mail clients block remote images). Email HTML needs inline CSS, which the inline_css Twig filter from the twig/cssinliner-extra package provides. Links must be absolute, so generate them with url() rather than path(); email has no "current host" (generating URLs).

Sending in the background

Talking to an SMTP server takes anywhere from tens of milliseconds to seconds, and it can fail. When Messenger is installed, Mailer already hands each message to the message bus as a SendEmailMessage. If you route that message class to a transport, sending happens in a worker instead of in the request:

YAML
# config/packages/messenger.yaml (real Symfony, read-only)
framework:
    messenger:
        routing:
            'Symfony\Component\Mailer\Messenger\SendEmailMessage': async

Now $mailer->send() only stores the message and returns, the user sees the next page immediately, and a worker started with messenger:consume async does the delivery, retrying temporary failures as described in the Messenger lesson. The trade-off is that a failure no longer reaches your controller: it shows up as a retry or in the failure transport, so monitor those.

Testing email

In the test environment, Symfony's test case helpers can assert what was sent without delivering anything:

PHP
// tests/Controller/SignupControllerTest.php (real Symfony, read-only)
public function testSignupSendsWelcomeEmail(): void
{
    $client = static::createClient();
    $client->request('POST', '/signup', ['email' => '[email protected]']);

    $this->assertEmailCount(1);
    $email = $this->getMailerMessage();
    $this->assertEmailHeaderSame($email, 'To', '[email protected]');
    $this->assertEmailTextBodyContains($email, 'Thanks for signing up');
}

An email flow you can run

Here is a stand-in with the same moving parts: a message builder, a tiny template renderer with escaping, transports, a failover transport and a queue that models "send in a worker". The classes are ours, not Symfony's.

PHP Email, transports, failover and a queue (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first send tries the primary, fails, and falls through to the backup, like failover(...). The template renderer escapes the context values, so the <script> in the name is harmless; Twig auto-escapes in the same way. In the asynchronous case the request code returns right after queueing and the worker does the delivery later. Finally, a message with no recipient fails fast with an exception, which is why real code wraps send() in try/catch (when sending synchronously).

Notifier: one message, several channels

Mailer sends email. Notifier (composer require symfony/notifier) sends a notification, a message that is independent of the channel, and decides how to deliver it for each recipient. The channels are email, sms, chat (Slack, Discord, Telegram and more), push and browser. Chat, SMS and push need a provider bridge package and a DSN, for example symfony/slack-notifier with SLACK_DSN.

PHP
// real Symfony, read-only
use Symfony\Component\Notifier\Notification\Notification;
use Symfony\Component\Notifier\NotifierInterface;
use Symfony\Component\Notifier\Recipient\Recipient;

public function alert(NotifierInterface $notifier, User $user): void
{
    $notification = (new Notification('Payment failed', ['email']))
        ->content('We could not charge your card for invoice 42.')
        ->importance(Notification::IMPORTANCE_URGENT);

    $notifier->send($notification, new Recipient($user->getEmail(), $user->getPhone()));
}

Two ways to choose channels. You can pass them explicitly, as above (['email']; a transport can be named as chat/slack). Or you can pass none and let the channel policy decide by importance (urgent, high, medium, low):

YAML
# config/packages/notifier.yaml (real Symfony, read-only)
framework:
    notifier:
        chatter_transports:
            slack: '%env(SLACK_DSN)%'
        texter_transports:
            twilio: '%env(TWILIO_DSN)%'
        channel_policy:
            urgent: ['sms', 'chat/slack', 'email']
            high: ['chat/slack', 'email']
            medium: ['email']
            low: ['email']

The recipient carries the contact details (Recipient(email, phone)), and for direct chat or SMS messages without a notification you can use ChatterInterface with ChatMessage and TexterInterface with SmsMessage. Like Mailer, Notifier messages can be sent through Messenger so the slow network calls happen in a worker.

flowchart LR
    N["Notification<br/>importance: urgent"] --> P["Channel policy"]
    P --> SMS["sms"]
    P --> CH["chat/slack"]
    P --> EM["email"]
    R["Recipient<br/>email, phone"] --> SMS
    R --> EM

The policy turns an importance level into channels; the recipient supplies the addresses each channel needs.

A notifier you can run

This stand-in applies a channel policy and skips channels that need contact details the recipient does not have. (That skipping is a choice made by this stand-in; check the Notifier documentation for how the real channels behave in your version.)

PHP Channel policy by importance (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

An urgent notification fans out to SMS, chat and email; a low-priority one is just an email. Bo has no phone number, so the stand-in skips the SMS channel for him. Changing the policy changes behaviour for every notification at once, without editing the code that sends them.

Choosing between them

  • Use Mailer when you need a rich email: attachments, templates, a specific sender.
  • Use Notifier when the same message may need to reach someone on different channels, or when the channel should depend on urgency.
  • For either, send in the background for anything that is not needed to finish the request, and always test with null://null or a catcher such as Mailpit before pointing at a real provider.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you tell Symfony Mailer which server or service to use?

    The DSN string (smtp://..., null://null, a provider scheme or failover(...)) configures the transport.
  2. 2. What does TemplatedEmail add compared with Email?

    TemplatedEmail uses htmlTemplate(), textTemplate() and context() so the body comes from Twig instead of a PHP string.
  3. 3. Messenger is installed and SendEmailMessage is routed to the async transport. What changes for your controller?

    The message is queued instead of delivered inline. Failures appear as retries or in the failure transport.
  4. 4. Which Notifier setting decides the channels when a notification does not list any?

    channel_policy maps each importance level to a list of channels.
  5. 5. Why use url() instead of path() for links in email templates?

    path() produces a root-relative link that means nothing in a mail client. url() includes scheme and host.

Summary

  • Mailer sends Email or TemplatedEmail objects through a transport chosen by MAILER_DSN; null://null and Mailpit are safe for development and tests.
  • Combine transports with failover(...) or roundrobin(...), and keep credentials out of version control.
  • With Messenger installed, route SendEmailMessage to an async transport so a worker sends the mail.
  • Notifier sends channel-independent notifications by email, SMS, chat, push or browser, using explicit channels or a policy by importance.
  • Test with the mailer assertions, and use absolute URLs in emails.

Next up: Scheduler, Lock and Cron Jobs.