3

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?

endo.anaconda
  • 2,449
  • 4
  • 29
  • 55
  • 1
    As you can see in the [`Symfony/Mailer::send()`](https://github.com/symfony/mailer/blob/5.4/Mailer.php) nothing is returned and the `TransportInterface` is not retrievable. You need to either create a custom `Mailer` service to mimic Symfony's or inject the `TransportInterface` service into your controller/service, to call [`$transport->send($message);`](https://github.com/symfony/mailer/blob/5.4/Transport/AbstractTransport.php#L59) directly instead. – Will B. Aug 10 '22 at 15:26

1 Answers1

1

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

endo.anaconda
  • 2,449
  • 4
  • 29
  • 55