What are the advantages of using a dedicated mailer class like PHPMailer or Swift Mailer instead of the built-in mail() function in PHP for sending emails with attachments?

When sending emails with attachments in PHP, using a dedicated mailer class like PHPMailer or Swift Mailer provides advantages such as better support for various email protocols (SMTP, sendmail, etc.), easier attachment handling, built-in security features to prevent email injection attacks, and better error handling capabilities compared to the basic mail() function.

// Example using PHPMailer to send an email with attachment
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer();
$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 = 'Test Email with Attachment';
$mail->Body = 'This is a test email with attachment.';

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

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