What are the advantages of using a Mailer class over the mail() function in PHP for email handling?

Using a Mailer class over the mail() function in PHP for email handling provides several advantages such as better encapsulation of email functionality, easier maintenance and testing, support for features like attachments and HTML emails, and the ability to easily switch between different email transport methods (e.g., SMTP, sendmail). Overall, using a Mailer class can lead to cleaner and more maintainable code for sending emails in PHP.

<?php
// Example of using a Mailer class for email handling

class Mailer {
    public function sendEmail($to, $subject, $message) {
        // Code to send email using a preferred email transport method (e.g., SMTP)
        echo "Email sent to $to with subject: $subject and message: $message";
    }
}

// Example of how to use the Mailer class to send an email
$mailer = new Mailer();
$mailer->sendEmail("recipient@example.com", "Hello", "This is a test email.");
?>