How can PHPMailer or other similar libraries help improve the reliability and security of email sending from PHP scripts?

When sending emails from PHP scripts, using PHPMailer or similar libraries can help improve reliability and security by providing features like SMTP authentication, encryption, error handling, and proper formatting of email headers. This can help prevent emails from being marked as spam, ensure delivery to recipients' inboxes, and protect against potential security vulnerabilities.

<?php
use PHPMailer\PHPMailer\PHPMailer;
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@example.com';
    $mail->Password = 'your_password';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');
    $mail->Subject = 'Subject of the Email';
    $mail->Body = 'This is the body of the email';

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