In what scenarios would it be beneficial to use a Mailer class instead of the built-in mail() function in PHP?

Using a Mailer class instead of the built-in mail() function in PHP can be beneficial in scenarios where you need more advanced features such as sending emails through SMTP, handling attachments, sending HTML emails, or managing email templates. A Mailer class can provide a more structured and reusable way to send emails in your application, making it easier to maintain and extend the email sending functionality.

<?php
class Mailer {
    private $mailer;

    public function __construct() {
        $transport = (new Swift_SmtpTransport('smtp.example.com', 587))
            ->setUsername('your_username')
            ->setPassword('your_password');

        $this->mailer = new Swift_Mailer($transport);
    }

    public function sendEmail($subject, $body, $to) {
        $message = (new Swift_Message($subject))
            ->setFrom(['your_email@example.com' => 'Your Name'])
            ->setTo($to)
            ->setBody($body);

        $this->mailer->send($message);
    }
}

// Example of using the Mailer class
$mailer = new Mailer();
$mailer->sendEmail('Subject', 'Hello, this is a test email.', 'recipient@example.com');
?>