What are the advantages of using a mailer class like Swiftmailer or PHPMailer over the mail() function in PHP?
Using a mailer class like Swiftmailer or PHPMailer provides several advantages over the mail() function in PHP. These classes offer more features, such as support for attachments, HTML emails, SMTP authentication, and better error handling. They also provide better security by automatically escaping dangerous characters and preventing header injection attacks.
// Example using PHPMailer to send an email
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->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;
}