What are some potential pitfalls of using the PHP mail() function for sending emails?
One potential pitfall of using the PHP mail() function is that it does not provide a reliable way to handle email delivery status or errors. To address this issue, you can use a library like PHPMailer which offers more robust features and better error handling capabilities.
// Example using PHPMailer library for sending emails
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php'; // Include PHPMailer autoload file
$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;
//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';
$mail->send();
echo 'Email has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}