Home >Backend Development >PHP Tutorial >How to Fix \'Mailer Error: SMTP connect() failed\' in PHPmailer?
Troubleshooting SMTP Connect() Failures in PHPmailer
Introduction
When attempting to send emails using PHPmailer, one might encounter the error "Mailer Error: SMTP connect() failed." This issue arises due to Google's implementation of a new authorization mechanism known as XOAUTH2.
Solution
To resolve this issue, follow these steps:
1. Enable Less Secure Apps in Google Account
2. Use TLS Over Port 587 Instead of SSL Over Port 465
Modify the code to use TLS over port 587 instead of SSL over port 465. Replace the following lines:
<code class="php">$mail->Host = "ssl://smtp.gmail.com"; $mail->Port = 465;</code>
with:
<code class="php">$mail->Host = 'smtp.gmail.com'; $mail->Port = 587;</code>
Sample Code
Here is the modified code:
<code class="php">require "class.phpmailer.php"; $mail = new PHPMailer(); $mail->IsSMTP(); // send via SMTP $mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only $mail->SMTPAuth = true; // turn on SMTP authentication $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail $mail->SMTPAutoTLS = false; $mail->Host = 'smtp.gmail.com'; $mail->Port = 587; $mail->Username = "[email protected]"; // SMTP username $mail->Password = "mypassword"; // SMTP password $webmaster_email = "[email protected]"; //Reply to this email ID $email="[email protected]"; // Recipients email ID $name="My Name"; // Recipient's name $mail->From = $webmaster_email; $mail->FromName = "My Name"; $mail->AddAddress($email,$name); $mail->AddReplyTo($webmaster_email,"My Name"); $mail->WordWrap = 50; // set word wrap $mail->IsHTML(true); // send as HTML $mail->Subject = "subject"; $mail->Body = "Hi, This is the HTML BODY "; //HTML Body $mail->AltBody = "This is the body when user views in plain text format"; //Text Body if(!$mail->Send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message has been sent"; }</code>
By implementing these changes, you should be able to successfully send emails using PHPmailer.
The above is the detailed content of How to Fix \'Mailer Error: SMTP connect() failed\' in PHPmailer?. For more information, please follow other related articles on the PHP Chinese website!