In what scenarios is it recommended to switch from using the PHP mail() function to a more robust email library like PHPMailer or SwiftMailer?
When dealing with complex email requirements such as sending HTML emails, attachments, or using SMTP authentication, it is recommended to switch from using the basic PHP mail() function to a more robust email library like PHPMailer or SwiftMailer. These libraries offer more features, better security, and easier customization for sending emails in PHP applications.
// Example using PHPMailer library
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->isHTML(true);
$mail->Subject = 'Subject';
$mail->Body = 'This is the HTML message body';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}