What are the advantages of using libraries like SwiftMailer or PHPMailer over the mail() function in PHP for sending emails?

Using libraries like SwiftMailer or PHPMailer over the mail() function in PHP provides advantages such as better support for attachments, HTML emails, SMTP authentication, and easier handling of complex email sending tasks.

// Example of sending an email using PHPMailer
require 'vendor/autoload.php'; // Include PHPMailer library

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@example.com';
    $mail->Password = 'yourpassword';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    $mail->isHTML(true);
    $mail->Subject = 'Subject of the email';
    $mail->Body = 'This is the HTML message body';

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