What are the advantages of using a library like PHPMailer for sending emails in PHP instead of the built-in mail() function?
Using a library like PHPMailer for sending emails in PHP provides several advantages over the built-in mail() function. PHPMailer offers better error handling, support for various email protocols (SMTP, sendmail, etc.), easier attachment handling, and better security features like SMTP authentication and SSL/TLS encryption.
<?php
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.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->isHTML(true);
$mail->Subject = 'Subject';
$mail->Body = 'Email body';
if($mail->send()) {
echo 'Email sent successfully';
} else {
echo 'Error sending email: ' . $mail->ErrorInfo;
}
?>