Symfony Mailer: sending and testing e-mails

Symfony Mailer builds an e-mail and hands it to a transport chosen by MAILER_DSN: SMTP, a sending service, or nothing at all in development.

// The sender is set once and for all in config/packages/mailer.yaml (headers: From).
$mailer->send((new Email())
    ->to($email)
    ->subject('Your table at the Drunken Dragon')
    ->text(sprintf('Hello %s, your table awaits you on %s.', $nom, $date->format('d/m/Y'))));

// In a functional test:
$this->assertEmailCount(1);

In the code, you build an Email (or a TemplatedEmail rendered by Twig) and pass it to MailerInterface; switching transports changes nothing in the code. What every e-mail shares, like the sender, is set once in config/packages/mailer.yaml. The traps lie around the sending: an e-mail that goes out at the wrong time, before the action is confirmed, or twice when a command is run again. Tests check it with assertions such as assertEmailCount().

The exercises have you send the tavern's scrolls: a booking confirmation, e-mails triggered by the transitions of a workflow, then a reminder command that can be run again without anyone receiving the same message twice.

4 exercises work on this concept, by writing code in the browser.

In the tracks

Related concepts

Workflow eventsDebuggingWorkflowGuardsConsole commandMigrations