Home >Backend Development >PHP Tutorial >How to Fix \'SMTP Connect() Failed\' Error When Sending Emails via Gmail?

How to Fix \'SMTP Connect() Failed\' Error When Sending Emails via Gmail?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-21 17:47:49967browse

How to Fix

SMTP Connection Failure: Resolving "SMTP Connect() failed" Error

In attempting to send emails using Gmail, you may encounter an error message stating "SMTP -> ERROR: Failed to connect to server: Connection timed out (110)nSMTP Connect() failed. Message was not sent.nMailer error: SMTP Connect() failed." This error indicates a problem with establishing a connection to the SMTP server.

To resolve this issue, you need to modify the PHP code responsible for sending emails. Specifically, remove or comment out the line:

<code class="php">$mail->IsSMTP();</code>

The IsSMTP() method is deprecated and should not be used. By removing or commenting out this line, the code will automatically use SMTP for sending emails, eliminating the connection issue and allowing successful email delivery.

Here is the updated code with the modification:

<code class="php">require 'class.phpmailer.php'; // path to the PHPMailer class
require 'class.smtp.php';

$mail = new PHPMailer();

$mail->Mailer = "smtp";
$mail->Host = "ssl://smtp.gmail.com";
$mail->Port = 587;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "[email&#160;protected]"; // SMTP username
$mail->Password = "mypasswword"; // SMTP password 
$Mail->Priority = 1;

$mail->AddAddress("[email&#160;protected]","Name");
$mail->SetFrom($visitor_email, $name);
$mail->AddReplyTo($visitor_email,$name);

$mail->Subject  = "Message from  Contact form";
$mail->Body     = $user_message;
$mail->WordWrap = 50;  

if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}</code>

The above is the detailed content of How to Fix \'SMTP Connect() Failed\' Error When Sending Emails via Gmail?. 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