In what ways can utilizing a mailer class in PHP improve the email sending functionality compared to the `mail()` function?
Using a mailer class in PHP can improve email sending functionality compared to the `mail()` function by providing a more object-oriented approach, better error handling, support for attachments, and easier configuration of SMTP settings. Mailer classes like PHPMailer or SwiftMailer offer a more robust and flexible solution for sending emails in PHP applications.
// Example using PHPMailer
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 = 'Email body content';
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo 'Email could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}