What are the advantages of using a dedicated mailer class like PHPmailer over the built-in mail() function?

When sending emails in PHP, using a dedicated mailer class like PHPMailer offers several advantages over the built-in mail() function. PHPMailer provides more features and options for sending emails, such as HTML email support, attachments, SMTP authentication, and error handling. It also has better security features to prevent email header injection and other vulnerabilities.

// Include the PHPMailer library
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Create a new PHPMailer instance
$mail = new PHPMailer();

// Set up the email parameters
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;

$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Subject of the email';
$mail->Body = 'This is the body of the email';

// Send the email
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}