Symfony TemplatedEmail: HTML e-mails rendered by Twig

TemplatedEmail, in Symfony Mailer, is an e-mail whose HTML content is rendered by a Twig template, with its context, like a page of the website.

$this->mailer->send((new TemplatedEmail())
    ->to(new Address($reservation->getEmail(), (string) $reservation->getNom()))
    ->subject('Your table at the Drunken Dragon')
    ->htmlTemplate('emails/confirmation.html.twig')
    ->context(['reservation' => $reservation]));

// In the template, an absolute link, which works from a mailbox:
// <a href="{{ url('app_menu') }}">See the menu</a>

The class comes from the Twig bridge, Symfony\Bridge\Twig\Mime\TemplatedEmail. You pick the template with htmlTemplate(), pass the variables with context(), and Symfony renders it all when sending, deriving from the HTML a text version for mail clients that don't display it. Putting these e-mails in a dedicated service avoids repeating the subject and template in every controller. Two traps: the email variable is reserved in the context, because the template receives the e-mail itself under that name; and path() produces /menu, a relative address that leads nowhere from a mailbox, whereas url() gives the full address. Styling, lacking a stylesheet, is written inline in the tags.

The exercises have you move the confirmation scroll from the controller to a service, the scroll-maker, with a real laid-out template and a link to the menu; then, for registrations to the storytelling evenings, send a scroll reminding them of the evening, only when the registration is saved, never when it's rejected.

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

In the tracks

Related concepts

Forms