Home >Backend Development >PHP Tutorial >SMTP Connect() Failed in PHPmailer: How to Fix the Error When Sending Emails with Google?

SMTP Connect() Failed in PHPmailer: How to Fix the Error When Sending Emails with Google?

DDD
DDDOriginal
2024-10-26 04:35:02745browse

SMTP Connect() Failed in PHPmailer: How to Fix the Error When Sending Emails with Google?

SMTP Connect() Failed in PHPmailer: A Detailed Solution

Sending emails using PHPmailer can be a straightforward task, but sometimes you may encounter errors such as "Mailer Error: SMTP connect() failed." This error can occur when attempting to connect to an SMTP server, typically due to incorrect configuration or security restrictions.

The problem you described is related to a change in Google's authorization mechanism for its SMTP server. Google now uses XOAUTH2 authentication, which requires additional steps to connect successfully.

Solution:

  1. Enable Less Secure App Access:

Visit https://www.google.com/settings/security/lesssecureapps and turn on "Allow less secure apps." This allows your application (PHPmailer) to interact with Google's SMTP server.

  1. Use TLS over Port 587:

Instead of SSL over port 465, switch to TLS over port 587. This is the recommended protocol for XOAUTH2 authentication.

  1. Configure PHPmailer:

In your PHPmailer code, make sure to use the following settings:

  • $mail->IsSMTP() = true;
  • $mail->SMTPDebug = 2; (for debugging)
  • $mail->SMTPAuth = true;
  • $mail->SMTPSecure = 'tls';
  • $mail->Host = 'smtp.gmail.com';
  • $mail->Port = 587;
  • $mail->Username = 'your_email_address';
  • $mail->Password = 'your_password';

By implementing these changes, your PHPmailer code should be able to connect successfully to the SMTP server and send emails without the "SMTP connect() failed" error.

Remember, always ensure proper security practices, such as enabling two-factor authentication for your email account and creating strong passwords for the mailserver.

The above is the detailed content of SMTP Connect() Failed in PHPmailer: How to Fix the Error When Sending Emails with Google?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn