How can the PHP code for sending emails be optimized for better performance and reliability?

One way to optimize PHP code for sending emails is to use a library like PHPMailer, which provides better performance and reliability compared to the built-in mail function. PHPMailer handles email sending in a more secure and efficient way, reducing the chances of emails being marked as spam or not being delivered.

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

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;

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

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