What are the advantages of using SMTP libraries like PHPMailer or Swift Mailer over the built-in mail() function?

When sending emails in PHP, using SMTP libraries like PHPMailer or Swift Mailer offers several advantages over the built-in mail() function. These libraries provide better error handling, support for multiple email attachments, HTML email formatting, SMTP authentication, and secure connections. Additionally, they offer more advanced features like email templating, debugging tools, and better compatibility with various email servers.

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

require 'vendor/autoload.php'; // Include PHPMailer library

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

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

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

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