What are best practices for handling error and failure tracking when using Swift Mailer in PHP?

When using Swift Mailer in PHP, it is important to implement error and failure tracking to ensure that any issues with sending emails are properly handled. One best practice is to set up event listeners to capture any errors or failures that occur during the email sending process. This allows you to log the errors, retry sending the email, or take other appropriate actions based on the specific error.

// Create the Swift Mailer instance
$transport = new Swift_SmtpTransport('smtp.example.com', 25);
$mailer = new Swift_Mailer($transport);

// Add event listeners for error and failure tracking
$mailer->registerPlugin(new Swift_Plugins_LoggerPlugin(new Swift_Plugins_Loggers_ArrayLogger()));
$mailer->registerPlugin(new Swift_Plugins_DecoratorPlugin(new Swift_Plugins_LoggerPlugin(new Swift_Plugins_Loggers_EchoLogger())));

// Create the message
$message = (new Swift_Message('Subject'))
    ->setFrom(['sender@example.com' => 'Sender Name'])
    ->setTo(['recipient@example.com' => 'Recipient Name'])
    ->setBody('Message body');

// Send the message
$result = $mailer->send($message);

// Check for errors or failures
if ($result) {
    echo 'Email sent successfully';
} else {
    echo 'Failed to send email. Check the logs for more information.';
}