What are the benefits of using PHPMailer for sending emails in PHP scripts?

Sending emails in PHP scripts can be challenging due to various reasons such as spam filters, authentication requirements, and formatting issues. PHPMailer is a popular library that simplifies the process of sending emails by providing a robust and reliable solution. It supports SMTP authentication, HTML emails, attachments, and more, making it a versatile tool for sending emails in PHP scripts.

<?php
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';

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

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

// Set up the SMTP settings
$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;

// Set the email content
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('to@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;
}