How can implementing a PHP mailer class like PHPMailer or SwiftMailer improve the email functionality in a contact form script compared to using the mail() function?

Using a PHP mailer class like PHPMailer or SwiftMailer can improve email functionality in a contact form script by providing more advanced features, better error handling, and improved security compared to using the basic mail() function. These classes offer support for SMTP authentication, HTML emails, attachments, and more, making them a more robust solution for sending emails from a contact form.

// Example code using PHPMailer to send an email from a contact form
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

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

try {
    //Server 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;

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

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

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