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

Using a PHP Mailer class over the traditional mail() function for sending emails offers several advantages, such as better support for attachments, HTML emails, SMTP authentication, and more robust error handling. PHP Mailer is also easier to use and provides a more object-oriented approach to sending emails.

// Include the PHP Mailer class
require 'path/to/PHPMailerAutoload.php';

// Create a new PHPMailer object
$mail = new PHPMailer;

// Set up the email parameters
$mail->setFrom('your@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Subject of the Email';
$mail->Body = 'Body of the Email';

// Attach a file if needed
$mail->addAttachment('/path/to/file.pdf');

// Send the email using SMTP
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;

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