How can PHP mail functionality be improved by using PHPMailer?

PHP mail functionality can be improved by using PHPMailer, a more robust and feature-rich library for sending emails in PHP. PHPMailer provides better support for sending HTML emails, attachments, SMTP authentication, and more reliable handling of email headers.

// Include the PHPMailer library
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Instantiate a new PHPMailer object
$mail = new PHPMailer();

// Set up the necessary configurations for sending emails
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_email@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;

// Set the email content, recipients, subject, etc.
$mail->setFrom('your_email@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Subject of the email';
$mail->Body = 'This is the HTML message body';

// Send the email
if($mail->send()){
    echo 'Email sent successfully';
} else {
    echo 'Error sending email: ' . $mail->ErrorInfo;
}