What are the advantages of using phpMailer over the standard PHP mail function for sending emails?
Using phpMailer over the standard PHP mail function provides several advantages such as better support for attachments, HTML emails, SMTP authentication, and more reliable delivery. phpMailer is also easier to use and provides better error handling compared to the standard PHP 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 = '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 = 'Email body content';
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo 'Email could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
Related Questions
- What steps can be taken to isolate and address PHP script inconsistencies that lead to errors like undefined variables?
- In what ways can inefficient database queries impact performance and resource usage in PHP applications?
- In PHP, what are the differences between server-side and client-side data evaluation when working with select fields?