What are the advantages of using a PHP mailer class over the mail() function for sending emails in PHP?

Using a PHP mailer class over the mail() function for sending emails in PHP offers several advantages, including better handling of email attachments, HTML emails, SMTP authentication, and error handling. PHP mailer classes provide a more robust and flexible solution for sending emails compared to the basic functionality offered by the mail() function.

// Example of using PHPMailer class to send an email
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

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

// Set up the SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

// Set email content
$mail->setFrom('from@example.com', 'Sender Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email';

// Send the email
if ($mail->send()) {
    echo 'Email sent successfully';
} else {
    echo 'Error sending email: ' . $mail->ErrorInfo;
}