Skip to content

Instantly share code, notes, and snippets.

@jkobus
Created January 4, 2024 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkobus/2cb5caba1c8d5beec93b7be41c90d05c to your computer and use it in GitHub Desktop.
Save jkobus/2cb5caba1c8d5beec93b7be41c90d05c to your computer and use it in GitHub Desktop.
Preview twig email in controller during development
<?php
namespace App\Controller;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mime\BodyRendererInterface;
use Symfony\Component\Routing\Attribute\Route;
class EmailViewController extends AbstractController
{
public function __construct(
private BodyRendererInterface $bodyRenderer
)
{
}
#[Route('/email/preview', name: 'email_view', condition: "'%kernel.environment%' === 'dev'")]
public function __invoke(): Response
{
$email = new TemplatedEmail();
$email->htmlTemplate('email/welcome.html.twig')
->context([
'name' => 'John Doe',
])
->subject('Welcome to the Space Bar!');
$this->bodyRenderer->render($email);
$html = (string) $email->getHtmlBody();
foreach ($email->getAttachments() as $attachment) {
if($attachment->getDisposition() === 'inline') {
$inlineMediaType = vsprintf('data:%s/%s;%s,', [
$attachment->getMediaType(),
$attachment->getMediaSubtype(),
$attachment->getPreparedHeaders()->get('Content-Transfer-Encoding')->getBody()
]);
$html = str_replace(
'cid:'.$attachment->getName(),
$inlineMediaType.$attachment->bodyToString(),
$html
);
}
}
return new Response($html);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment