Search code examples
phpsymfonysymfony-mailer

How to get the rendered body of a templated email before sending?


I want to get the render of an email before to send it.

I created a TemplatedEmail with htmlTemplate and context, it works fine for sending but how get the generated template with context to save it in database ? (customer needs)

I tried the getBody() but seems to work only with text template as I get A message must have a text or an HTML part or attachments.

$email = new TemplatedEmail();
$email->htmlTemplate($htmlTemplate);
$email->from($from)->to(...$to)->subject($subject);
$email->context($context);

dd($email->getBody());

I thought to use the render method but I'm in a service and not sure if it's a good way to store in database.


Solution

  • Symfony only renders the message when actually sending it, via an Event Listener. The class responsible from doing the rendering is BodyRenderer, from the Twig Bridge.

    But nothing stops you from rendering the message yourself.

    You have the template and the context variables, so you could simply inject Twig wherever you are doing the sending, render the template to a string and do whatever you need with that.

    You could also register your own MessageEvent::class listener, set it with lower priority than the one registered by the Twig Bundle (it uses the default priority) so it's executed after that one, and then you could access the message body since it would have been rendered already. This is (very) slightly more complex, but you'd gain some performance since you wouldn't be rendering the template twice.

    Which approach to use would depend on your application, your constraints, etc. But the important bit is to realize on what part of the process you'll find the body actually rendered, or render it yourself if you want it before that.