How can PHPMailer be used to send emails in a more reliable and secure manner compared to the mail() function?
Using PHPMailer allows for more reliable and secure email sending compared to the mail() function because PHPMailer supports SMTP authentication, encryption protocols like SSL and TLS, error handling, and better handling of attachments and HTML content.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
//Server settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
//Recipients
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
//Content
$mail->isHTML(true);
$mail->Subject = 'Subject';
$mail->Body = 'Email body content';
$mail->send();
echo 'Email has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Related Questions
- What are the security implications of allowing users to delete or rename files on the server using PHP scripts?
- What are the advantages and disadvantages of using SELECT * in SQL queries within PHP scripts?
- What are some best practices for handling line breaks in PHP loops based on specific conditions?