How can the PHP code for sending confirmation emails be improved for efficiency and reliability?
Issue: The PHP code for sending confirmation emails can be improved for efficiency and reliability by using a library like PHPMailer, which provides robust email sending functionality with built-in error handling and support for various email protocols.
<?php
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 = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Recipient
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
// Content
$mail->isHTML(true);
$mail->Subject = 'Confirmation Email';
$mail->Body = 'This is a confirmation email.';
// Send the email
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo "Email could not be sent. Mailer Error: {$mail->ErrorInfo}";
}