How can the PHP mail() function be improved for more reliable email delivery?
The PHP mail() function can be improved for more reliable email delivery by using a library like PHPMailer or Swift Mailer. These libraries provide more advanced features such as SMTP authentication, error handling, and better support for attachments. By using one of these libraries, you can ensure that your emails are delivered more consistently and reliably.
// Example using PHPMailer library for improved email delivery
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 = 'ssl';
$mail->Port = 465;
//Recipients
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
//Content
$mail->isHTML(true);
$mail->Subject = 'Subject';
$mail->Body = 'Email body content';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}