What are the advantages of using an SMTP server with a library like phpmailer or Swift for sending emails over using the built-in mail() function in PHP?

When sending emails in PHP, using an SMTP server with a library like phpmailer or Swift offers several advantages over the built-in mail() function. These libraries provide more advanced features such as SMTP authentication, error handling, HTML email support, attachments, and better control over the email sending process. Additionally, using an SMTP server can improve email deliverability rates and reduce the chances of emails being marked as spam.

// Example using PHPMailer library to send an email via SMTP

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

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your_smtp_username';
    $mail->Password = 'your_smtp_password';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');
    $mail->isHTML(true);
    $mail->Subject = 'Subject';
    $mail->Body = 'Email body';

    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo "Email could not be sent. Mailer Error: {$mail->ErrorInfo}";
}