I use symfonymailer the way described in Sending Emails with Mailer/Debugging emails
The SentMessage object returned by the send() method of the TransportInterface provides access to the original message (getOriginalMessage()) and to some debug information (getDebug()) such as the HTTP calls done by the HTTP transports, which is useful to debug errors.
The way i use it currently:
public function __construct(private MailerInterface $mailer)
try
{
$this->mailer->send($message);
}
catch (TransportExceptionInterface $e)
{
echo $e->getDebug();
}
Since $this->mailer->send($message) is an MailerInterface it returns nothing. By having SentMessage object all the information about the sent mail would be present.
How can I retrieve the SentMessage object when sending the mail?
Here is the solution I found:
public function __construct(private TransportInterface $mailer, private Environment $twig)
public function sendMail(Email $message): void
{
//If template is used, render it
if (!empty($message->getHtmlTemplate())){
$renderedHtmlBody = $this->twig->render($message->getHtmlTemplate(), $message->getContext());
$message->html($renderedHtmlBody);
$textContent = new Html2Text($renderedHtmlBody, ['do_links' => 'table');
$message->text(trim($textContent->getText()));
}
try {
$message = $this->mailer->send($message);
} catch (TransportExceptionInterface $e) {
...
}
}
If you use a TemplatedEmail then the template will be rendered when sending. So a twig-template must be rendered before sending and filled in the $message body for html and plain-text before sending.
Plain-text mails Html2Text is used to have a clean text-output
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With