How can the use of a Mailer class in PHP improve the reliability and deliverability of emails compared to using the mail() function?

When using the mail() function in PHP to send emails, there is a higher chance of emails being marked as spam or not being delivered due to various reasons such as missing headers or incorrect configurations. By using a Mailer class, we can ensure that all necessary headers are included, connections are properly established, and emails are sent through a reliable SMTP server, improving the reliability and deliverability of emails.

<?php
require 'vendor/autoload.php'; // Include the required library

// Create a new instance of the Mailer class
$mailer = new Mailer();

// Set up the necessary configurations
$mailer->setServer('smtp.example.com', 'username', 'password');
$mailer->setFrom('sender@example.com', 'Sender Name');
$mailer->addTo('recipient@example.com', 'Recipient Name');
$mailer->setSubject('Subject of the Email');
$mailer->setBody('Body of the Email');

// Send the email
if($mailer->send()){
    echo 'Email sent successfully';
} else {
    echo 'Failed to send email';
}
?>