SMTP Connect Failure in PHPmailer: Resolving the Issue
When sending emails through PHPmailer, developers may encounter an error: "Mailer Error: SMTP connect() failed." This problem often arises when utilizing Gmail's SMTP server.
The solution lies in Google's implementation of a new authorization mechanism, XOAUTH2. To allow PHPmailer to connect to Gmail's SMTP, you must enable the "Less Secure Apps" setting in your Google account. This step grants access to applications that do not adhere to strict encryption protocols.
Additionally, instead of using SSL over port 465, switch to TLS over port 587. TLS ensures that your requests are securely encrypted, meeting Google's requirements.
Below is a modified code snippet that incorporates these changes:
require_once 'C:\xampp\htdocs\email\vendor\autoload.php';
define ('GUSER','[email protected]');
define ('GPWD','your password');
// make a separate file and include this file in that. call this function in that file.
function smtpmailer($to, $from, $from_name, $subject, $body) {
global $error;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->SMTPAutoTLS = false;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo;
return false;
} else {
$error = 'Message sent!';
return true;
}
}
By implementing these modifications, you can successfully establish a connection to Gmail's SMTP server and transmit emails through PHPmailer.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3