What are best practices for setting up PHP Mailer to work with Gmail SMTP?
When setting up PHP Mailer to work with Gmail SMTP, it's important to properly configure the SMTP settings in your PHP script. This includes setting the host to "smtp.gmail.com", the port to 587, and enabling SMTP authentication with your Gmail email address and password. Additionally, you may need to enable "less secure apps" access in your Gmail account settings.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@gmail.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('your@gmail.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->isHTML(true);
$mail->Subject = 'Subject';
$mail->Body = 'Message body';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
Keywords
Related Questions
- What best practices should be followed when using img elements in PHP to display images on a webpage?
- What are some alternative methods or libraries in PHP that can simplify the process of working with complex JSON data structures from APIs?
- In PHP, what are the implications of including HTML elements like links within PHP code, and how can this impact functionality and best practices?