What are the benefits of using a PHP mailer class like PHPMailer instead of the built-in mail function?
Using a PHP mailer class like PHPMailer instead of the built-in mail function provides additional features and functionality, such as SMTP authentication, HTML email support, file attachment capabilities, and better error handling. This can help improve the deliverability of emails and make it easier to send complex emails with various formatting options.
<?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 is the correct way to concatenate date and time strings in PHP for MySQL DateTime storage?
- What are the potential risks of storing PHP code in a MySQL database?
- How can PHP developers prevent browsers from modifying the HTTP_REFERER header and affecting the reliability of the referrer information?