What are the advantages of using PHPMailer over the native mail() function in PHP for sending emails?
The main advantages of using PHPMailer over the native mail() function in PHP for sending emails include better support for attachments, HTML emails, SMTP authentication, and error handling. PHPMailer is a more robust and flexible solution for sending emails compared to the basic functionality provided by the mail() function.
<?php
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 = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email sent using PHPMailer';
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
?>