In what situations is it recommended to use a Mailer class instead of the mail() function in PHP for sending emails, and how can it improve email delivery reliability?

When sending emails in PHP, it is recommended to use a Mailer class instead of the mail() function when dealing with complex email requirements, such as sending HTML emails, handling attachments, or sending emails via SMTP. Using a Mailer class can improve email delivery reliability by providing better error handling, support for authentication, and easier customization of email headers.

// Example of using PHPMailer library for sending emails
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@example.com';
    $mail->Password = 'yourpassword';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    $mail->isHTML(true);
    $mail->Subject = 'Subject';
    $mail->Body = 'Email body';

    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'Email could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}