Created
January 4, 2024 16:38
-
-
Save jkobus/2cb5caba1c8d5beec93b7be41c90d05c to your computer and use it in GitHub Desktop.
Preview twig email in controller during development
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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