Ошибка smtp failed to connect to server connection timed out 110

Problem description I have been using an old version of phpmailer for many years with success (on a shared server) with the following code: Please check http://www.crmpt.com/email_test_send_old.php...

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@pipesportugal

Problem description

I have been using an old version of phpmailer for many years with success (on a shared server) with the following code:
Please check http://www.crmpt.com/email_test_send_old.php

Code to reproduce

<?php
require_once("phpmailer/class.phpmailer.php");  
$mail = new PHPMailer();  
$mail->IsSMTP();  // telling the class to use SMTP  
$mail->Host     = "localhost"; // SMTP server  
$mail->SMTPAuth = true;     // turn on SMTP authentication
$mail->Username = "2e@afaturar.com";  // SMTP username
$mail->Password = "TemporaryPass123"; // SMTP password 
$mail->From = "2e@afaturar.com";
$mail->FromName = "TEST COMPANY";
$mail->AddReplyTo("ca@mz2e.com","2E");
$mail->AddCC("jose.jc.almeida@hotmail.com"); // name is optional
$mail->AddBCC("jose.jc.almeida@gmail.com");  // name is optional
$emailtosend = "ca@mz2e.com";
$mail->AddAddress("$emailtosend"); 
$mail->WordWrap = 50;                                 // set word wrap to 50 characters
$mail->IsHTML(true);                                  // set email format to HTML
$mail->Subject = "EMAIL TEST";
$mail->Body    = nl2br("EMAIL TEST ** EMAIL TEST ** EMAIL TEST **");  
$mail->AltBody = nl2br("EMAIL TEST ** EMAIL TEST ** EMAIL TEST **");

if(!$mail->Send()) {  
 echo "<br>Email not sent !!<br> ERRO: $mail->ErrorInfo<br>"; 
 echo "<br>mail->From = $mail->From<br>"; 
 echo "<br>mail->AddAddress = $emailtosend<br>"; 
}  
?>

Debug output

1 or 2 weeks ago, my provider must have changed some server settings (I don’t know) and I started receiving:
SMTP Error: Could not connect to SMTP host.

PRESENT SITUATION:

Problem description

Because of the above problem, I moved to phpmailer6, but still having no success.
please check:
http://www.crmpt.com/email_test_send_new.php

Code to reproduce

<?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require 'phpmailer6/src/PHPMailer.php';
require 'phpmailer6/src/SMTP.php';
require 'phpmailer6/src/Exception.php';
$mail = new PHPMailer(true);  
try {
     $mail->SMTPDebug = 2;  
     $mail->isSMTP();  // telling the class to use SMTP  
	 $mail->Host = "mail.afaturar.com"; // SMTP server  
	 $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
     $mail->Port = 587;  
	 $mail->SMTPAuth = true;     // turn on SMTP authentication
     $mail->Username = "2e@afaturar.com";  // SMTP username
     $mail->Password = "TemporaryPass123"; // SMTP password 
	 $mail->setFrom("2e@afaturar.com");
     $emailtosendto = "ca@mz2e.com";
	 $mail->addAddress("$emailtosendto");  
     $mail->addReplyTo("ca@mz2e.com","2E");
     $mail->addCC("jose.jc.almeida@hotmail.com"); // name is optional
     $mail->addBCC("jose.jc.almeida@gmail.com");  // name is optional
     $mail->isHTML(true);                         // set email format to HTML
     $mail->Subject = "EMAIL TEST";
     $mail->Body    = nl2br("EMAIL TEST ** EMAIL TEST ** EMAIL TEST **");  
     $mail->AltBody = nl2br("EMAIL TEST ** EMAIL TEST ** EMAIL TEST **");
     $mail->send();
}
catch (Exception $e) {
    echo 'Message could not be sent(phpmailer6).<br>';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}
?>

Debug output

2017-10-29 07:00:47 SMTP ERROR: Failed to connect to server: Connection timed out (110)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Message could not be sent(phpmailer6).
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Thank you so much for all the help.
Regards
Jose.

@Synchro

Well don’t just change the code and hope it works, figure out the cause. It’s most likely that your ISP has started blocking outbound SMTP. Diagnosing this is covered in the troubleshooting guide linked from the error.

@pipesportugal

@Synchro
I have complained to my Hosting provider (vodahost) and their reply was:

Hello,

I’ve checked and could not find any issues from our end also we didn’t make any changes from our side. It seems the issue with your phpmailer script. Please check with the script from your and let me know if any changes need to be made from our end.

Regards,

The above is the configuration recommended by vodahost:

imagem

According to their instructions, I changed the following part of my code accordingly:

$mail->Host = "voda4.vodahost4.com"; // SMTP server  
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; //587 tls  

I also tested the ssl and it is loaded. Please check:
http://www.crmpt.com/teste_ssl.php

This same email is being used to send emails, without any problem from Microsoft Outlook, so if this was to be a block from vodahost on outbond SMTP, it would not be possible for Outlook to perform that task, right ?

Thanks for your help Mr Bointon,

Regards
Jose

2 participants

@Synchro

@pipesportugal

Am trying to send mail to a gmail address but it keeps on getting this error «SMTP -> ERROR: Failed to connect to server: Connection timed out (110)SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed.» What could be the problem?

        require 'class.phpmailer.php'; // path to the PHPMailer class
        require 'class.smtp.php';

            $mail = new PHPMailer();


            $mail->IsSMTP();  // telling the class to use SMTP
            $mail->SMTPDebug = 2;
            $mail->Mailer = "smtp";
            $mail->Host = "ssl://smtp.gmail.com";
            $mail->Port = 587;
            $mail->SMTPAuth = true; // turn on SMTP authentication
            $mail->Username = "myemail@gmail.com"; // SMTP username
            $mail->Password = "mypasswword"; // SMTP password 
            $Mail->Priority = 1;

            $mail->AddAddress("myemail@gmail.com","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.';
            }

AnFi's user avatar

AnFi

10.3k3 gold badges22 silver badges46 bronze badges

asked Aug 28, 2013 at 19:29

Muli's user avatar

4

Remove or comment out the line-

$mail->IsSMTP();

And it will work for you.

I have checked and experimented many answers from different sites but haven’t got any solution except the above solution.

dario's user avatar

dario

5,11912 gold badges27 silver badges32 bronze badges

answered Aug 10, 2015 at 12:51

Snehasis's user avatar

SnehasisSnehasis

9156 silver badges10 bronze badges

17

You must to have installed php_openssl.dll, if you use wampserver it’s pretty easy, search and apply the extension for PHP.

In the example change this:

    //Set the hostname of the mail server
    $mail->Host = 'smtp.gmail.com';

    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission 465 ssl
    $mail->Port = 465;

    //Set the encryption system to use - ssl (deprecated) or tls
    $mail->SMTPSecure = 'ssl';

and then you recived an email from gmail talking about to enable the option to Less Safe Access Applications
here https://www.google.com/settings/security/lesssecureapps

I recommend you change the password and encrypt it constantly

answered Oct 8, 2014 at 2:03

El David's user avatar

El DavidEl David

5967 silver badges16 bronze badges

2

You’ve got no SMTPSecure setting to define the type of authentication being used, and you’re running the Host setting with the unnecessary ‘ssl://’ (PS — ssl is over port 465, if you need to run it over ssl instead, see the accepted answer here. Here’s the lines to add/change:

+ $mail->SMTPSecure = 'tls';

- $mail->Host = "ssl://smtp.gmail.com";
+ $mail->Host = "smtp.gmail.com";

Community's user avatar

answered Aug 29, 2013 at 20:58

Dmitri DB's user avatar

Dmitri DBDmitri DB

3173 silver badges15 bronze badges

4

Are you running on Localhost? and have you edit the php.ini ?

If not yet, try this:
1. Open xampp->php->php.ini
2. Search for extension=php_openssl.dll
3. The initial will look like this ;extension=php_openssl.dll
4. Remove the ‘;’ and it will look like this extension=php_openssl.dll
5. If you can’t find the extension=php_openssl.dll, add this line extension=php_openssl.dll.
6. Then restart your Xampp.

Goodluck ;)

answered Jan 11, 2014 at 4:03

Sendoh Akira's user avatar

1

I know its been a while since this question but I had the exact problem and solved it by disabling SMTP_BLOCK on csf.conf (we use CSF for a firewall).

To disable just edit csf.conf and disable SMTP_BLOCK like so:

###############################################################################
# SECTION:SMTP Settings
###############################################################################
# Block outgoing SMTP except for root, exim and mailman (forces scripts/users
# to use the exim/sendmail binary instead of sockets access). This replaces the
# protection as WHM > Tweak Settings > SMTP Tweaks
#
# This option uses the iptables ipt_owner/xt_owner module and must be loaded
# for it to work. It may not be available on some VPS platforms
#
# Note: Run /etc/csf/csftest.pl to check whether this option will function on
# this server
# SMTP_BLOCK = "1" --> this will cause phpmailer Connection timed out (110)
SMTP_BLOCK = "0"

answered Jan 23, 2016 at 20:32

Goldbug's user avatar

GoldbugGoldbug

6076 silver badges8 bronze badges

1

i’ve had this problem in tell i recive an email from google telling me that someone try to login to your account is it you and i answer yes then it start workin so if this is the case for you look in your email and allow the server

answered Jul 16, 2016 at 12:59

user5778000's user avatar

2

Login your Google account at myaccount.google.com/security go to «Login» and then «Security», scroll to bottom then enable the «Allow less secure apps» option.

Daniel's user avatar

Daniel

1,23914 silver badges24 bronze badges

answered Dec 27, 2016 at 22:07

Hieu - 7347514's user avatar

Here is a list of this you should look into when dealing with PHPMailer:

  1. Enable openSSL by un-commenting extension=php_openssl.dll in your PHP.ini
  2. Use $mail->SMTPSecure = 'tls'; and $mail->Port = 587;
  3. Enable debugging for if you are going wrong somewhere else like incorrect username and password etc.

answered May 14, 2015 at 7:02

KKK's user avatar

KKKKKK

3,1295 gold badges34 silver badges58 bronze badges

You are doing all well. Just you have to check different SMTP ports like 465 and others that works on your system.
Another thing to keep in mind to allow access to the less secure apps by google account otherwise it throws the same error.
I have gone through it for a whole day and the only thing I am doing wrong is the port no., I just changed the port no. and it works.

answered Mar 7, 2017 at 13:59

Deepak Kumar's user avatar

Deepak KumarDeepak Kumar

6621 gold badge8 silver badges22 bronze badges

Mailjet

SMTP SETTINGS

Port: 25 or 587 (some providers block port 25)

I work by changing the port after deploying the app to the server.

  • In Debug it worked for me: $mail->Port = 25;
  • In Release it worked for me: $mail->Port = 587;

GL

answered Dec 19, 2018 at 2:13

Braian Coronel's user avatar

Braian CoronelBraian Coronel

21.6k4 gold badges53 silver badges59 bronze badges

To get it working, I had to go to myaccount.google.com -> «connected apps & sites», and turn «Allow less secure apps» to «ON» (near the bottom of the page).

answered Aug 1, 2017 at 9:19

Akif Hussain Sayyed's user avatar

If it works on your localhost but not on your web host:

Some hosting sites block certain outbound SMTP ports. Commenting out the line $mail->IsSMTP(); as noted in the accepted answer may make it work, but it is simply disabling your SMTP configuration, and using the hosting site’s email config.

If you are using GoDaddy, there is no way to send mail using a different SMTP. I was using SiteGround, and found that they were allowing SMTP access from ports 25 and 465 only, with an SSL encryption type, so I would look up documentation for your host and go from there.

answered Apr 6, 2018 at 22:06

Stephanie's user avatar

StephanieStephanie

1332 silver badges7 bronze badges

        <?php
    require 'PHPMailer/PHPMailerAutoload.php';
    
    $mail = new PHPMailer();
    
    $mail->SMTPDebug = 0;                               // Enable verbose debug output
    
    
    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->IsSMTP();
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'mail@gmail.com';                 // SMTP username
    $mail->Password = 'your pass';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    $mail->setFrom('mail@gmail.com');
    $mail->addAddress('mail@gmail.com');               // Name is optional
    
    
    $mail->isHTML(true);                                  // Set email format to HTML
    
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    
    if(!$mail->send()) {
        echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }
    
  ?>

THIS WORK FOR ME JUST WHEN YOU WANT TO TEST
DON’T USE IDE FOR TESTING THAT BECAUSE PROBABLY NOT WORK IF YOU IN LOCALHOST USE localhost/yourfile.php

answered Mar 17, 2021 at 16:56

MAX's user avatar

the solution is configure the gmail preferences, access to no secure application

CSchulz's user avatar

CSchulz

10.7k10 gold badges59 silver badges112 bronze badges

answered Jun 6, 2016 at 3:12

marcelo's user avatar

0

Am trying to send mail to a gmail address but it keeps on getting this error «SMTP -> ERROR: Failed to connect to server: Connection timed out (110)SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed.» What could be the problem?

        require 'class.phpmailer.php'; // path to the PHPMailer class
        require 'class.smtp.php';

            $mail = new PHPMailer();


            $mail->IsSMTP();  // telling the class to use SMTP
            $mail->SMTPDebug = 2;
            $mail->Mailer = "smtp";
            $mail->Host = "ssl://smtp.gmail.com";
            $mail->Port = 587;
            $mail->SMTPAuth = true; // turn on SMTP authentication
            $mail->Username = "myemail@gmail.com"; // SMTP username
            $mail->Password = "mypasswword"; // SMTP password 
            $Mail->Priority = 1;

            $mail->AddAddress("myemail@gmail.com","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.';
            }

AnFi's user avatar

AnFi

10.3k3 gold badges22 silver badges46 bronze badges

asked Aug 28, 2013 at 19:29

Muli's user avatar

4

Remove or comment out the line-

$mail->IsSMTP();

And it will work for you.

I have checked and experimented many answers from different sites but haven’t got any solution except the above solution.

dario's user avatar

dario

5,11912 gold badges27 silver badges32 bronze badges

answered Aug 10, 2015 at 12:51

Snehasis's user avatar

SnehasisSnehasis

9156 silver badges10 bronze badges

17

You must to have installed php_openssl.dll, if you use wampserver it’s pretty easy, search and apply the extension for PHP.

In the example change this:

    //Set the hostname of the mail server
    $mail->Host = 'smtp.gmail.com';

    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission 465 ssl
    $mail->Port = 465;

    //Set the encryption system to use - ssl (deprecated) or tls
    $mail->SMTPSecure = 'ssl';

and then you recived an email from gmail talking about to enable the option to Less Safe Access Applications
here https://www.google.com/settings/security/lesssecureapps

I recommend you change the password and encrypt it constantly

answered Oct 8, 2014 at 2:03

El David's user avatar

El DavidEl David

5967 silver badges16 bronze badges

2

You’ve got no SMTPSecure setting to define the type of authentication being used, and you’re running the Host setting with the unnecessary ‘ssl://’ (PS — ssl is over port 465, if you need to run it over ssl instead, see the accepted answer here. Here’s the lines to add/change:

+ $mail->SMTPSecure = 'tls';

- $mail->Host = "ssl://smtp.gmail.com";
+ $mail->Host = "smtp.gmail.com";

Community's user avatar

answered Aug 29, 2013 at 20:58

Dmitri DB's user avatar

Dmitri DBDmitri DB

3173 silver badges15 bronze badges

4

Are you running on Localhost? and have you edit the php.ini ?

If not yet, try this:
1. Open xampp->php->php.ini
2. Search for extension=php_openssl.dll
3. The initial will look like this ;extension=php_openssl.dll
4. Remove the ‘;’ and it will look like this extension=php_openssl.dll
5. If you can’t find the extension=php_openssl.dll, add this line extension=php_openssl.dll.
6. Then restart your Xampp.

Goodluck ;)

answered Jan 11, 2014 at 4:03

Sendoh Akira's user avatar

1

I know its been a while since this question but I had the exact problem and solved it by disabling SMTP_BLOCK on csf.conf (we use CSF for a firewall).

To disable just edit csf.conf and disable SMTP_BLOCK like so:

###############################################################################
# SECTION:SMTP Settings
###############################################################################
# Block outgoing SMTP except for root, exim and mailman (forces scripts/users
# to use the exim/sendmail binary instead of sockets access). This replaces the
# protection as WHM > Tweak Settings > SMTP Tweaks
#
# This option uses the iptables ipt_owner/xt_owner module and must be loaded
# for it to work. It may not be available on some VPS platforms
#
# Note: Run /etc/csf/csftest.pl to check whether this option will function on
# this server
# SMTP_BLOCK = "1" --> this will cause phpmailer Connection timed out (110)
SMTP_BLOCK = "0"

answered Jan 23, 2016 at 20:32

Goldbug's user avatar

GoldbugGoldbug

6076 silver badges8 bronze badges

1

i’ve had this problem in tell i recive an email from google telling me that someone try to login to your account is it you and i answer yes then it start workin so if this is the case for you look in your email and allow the server

answered Jul 16, 2016 at 12:59

user5778000's user avatar

2

Login your Google account at myaccount.google.com/security go to «Login» and then «Security», scroll to bottom then enable the «Allow less secure apps» option.

Daniel's user avatar

Daniel

1,23914 silver badges24 bronze badges

answered Dec 27, 2016 at 22:07

Hieu - 7347514's user avatar

Here is a list of this you should look into when dealing with PHPMailer:

  1. Enable openSSL by un-commenting extension=php_openssl.dll in your PHP.ini
  2. Use $mail->SMTPSecure = 'tls'; and $mail->Port = 587;
  3. Enable debugging for if you are going wrong somewhere else like incorrect username and password etc.

answered May 14, 2015 at 7:02

KKK's user avatar

KKKKKK

3,1295 gold badges34 silver badges58 bronze badges

You are doing all well. Just you have to check different SMTP ports like 465 and others that works on your system.
Another thing to keep in mind to allow access to the less secure apps by google account otherwise it throws the same error.
I have gone through it for a whole day and the only thing I am doing wrong is the port no., I just changed the port no. and it works.

answered Mar 7, 2017 at 13:59

Deepak Kumar's user avatar

Deepak KumarDeepak Kumar

6621 gold badge8 silver badges22 bronze badges

Mailjet

SMTP SETTINGS

Port: 25 or 587 (some providers block port 25)

I work by changing the port after deploying the app to the server.

  • In Debug it worked for me: $mail->Port = 25;
  • In Release it worked for me: $mail->Port = 587;

GL

answered Dec 19, 2018 at 2:13

Braian Coronel's user avatar

Braian CoronelBraian Coronel

21.6k4 gold badges53 silver badges59 bronze badges

To get it working, I had to go to myaccount.google.com -> «connected apps & sites», and turn «Allow less secure apps» to «ON» (near the bottom of the page).

answered Aug 1, 2017 at 9:19

Akif Hussain Sayyed's user avatar

If it works on your localhost but not on your web host:

Some hosting sites block certain outbound SMTP ports. Commenting out the line $mail->IsSMTP(); as noted in the accepted answer may make it work, but it is simply disabling your SMTP configuration, and using the hosting site’s email config.

If you are using GoDaddy, there is no way to send mail using a different SMTP. I was using SiteGround, and found that they were allowing SMTP access from ports 25 and 465 only, with an SSL encryption type, so I would look up documentation for your host and go from there.

answered Apr 6, 2018 at 22:06

Stephanie's user avatar

StephanieStephanie

1332 silver badges7 bronze badges

        <?php
    require 'PHPMailer/PHPMailerAutoload.php';
    
    $mail = new PHPMailer();
    
    $mail->SMTPDebug = 0;                               // Enable verbose debug output
    
    
    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->IsSMTP();
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'mail@gmail.com';                 // SMTP username
    $mail->Password = 'your pass';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    $mail->setFrom('mail@gmail.com');
    $mail->addAddress('mail@gmail.com');               // Name is optional
    
    
    $mail->isHTML(true);                                  // Set email format to HTML
    
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    
    if(!$mail->send()) {
        echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }
    
  ?>

THIS WORK FOR ME JUST WHEN YOU WANT TO TEST
DON’T USE IDE FOR TESTING THAT BECAUSE PROBABLY NOT WORK IF YOU IN LOCALHOST USE localhost/yourfile.php

answered Mar 17, 2021 at 16:56

MAX's user avatar

the solution is configure the gmail preferences, access to no secure application

CSchulz's user avatar

CSchulz

10.7k10 gold badges59 silver badges112 bronze badges

answered Jun 6, 2016 at 3:12

marcelo's user avatar

0

These days, an option to send mails is a basic requirement of any web application.

So popular applications like WordPress, Drupal etc. include a mail program called “PHPMailer” for sending mails.

The steps to setup PHPMailer may not be intuitive to many website owners and mistakes in configuration often cause “Smtp error: Failed to connect to server” error.

As part of our Support Services, we help website owners solve their technical issues. And, mail issue related with PHPMailer is an error that we see often .

In this article, we’ll see the top reasons for “Smtp error: Failed to connect” and how we fix them.

What is “Smtp error: Failed to connect to server” ?

Spammers often use php scripts that directly connect to remote servers and send spam mails.

To defend this, many Web Hosting providers block direct connection from websites to external mail servers.

In such servers, mails from website can be sent only via its own mail server (SMTP server) port, just as how Outlook or Windows Mail works.

PHPMailer is a mail application that works like a mail client and helps to send mail via SMTP server.

But, PHPMailer do not work out of the box. It can fail due to firewall restrictions on the server, wrong mail server name, port etc. and shows the error:

“Smtp error: Failed to connect to server”

And, depending on the response from the mail server, we’ve seen 2 variations of this error :

SMTP ERROR: Failed to connect to server: Connection refused (111)

or

SMTP ERROR: Failed to connect to server: Connection timed out (110)

What causes SMTP ERROR: Failed to connect to server ?

Here, let us discuss the top reasons for “SMTP ERROR: Failed to connect to server”.

1. SMTP restrictions on the server.

Servers restrict the programs that can directly connect to remote servers and send mail. Usually, only mail server, root user etc. allow SMTP connections.

For example, CPanel servers block access to external SMTP servers using the “SMTP Restrictions” option.

With this restriction, connection from PHPMailer to an external mail server do not work. The connection wait for some time and eventually die with the following error:

2018-10-12 04:12:37 SMTP ERROR: Failed to connect to server: Connection timed out (110)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Oops! Something went wrong and we couldn't send your message.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

2. Firewall restrictions on the server

Mail servers accept or reject connections based on certain firewall policies.

All mail servers allow the connection from default mail port 25. Bu,t other mail ports like 465, 587 etc. will not be open in many servers.

On a server with mail port restrictions, when a website owner tries to send mail using an external smtp server on port 465, it ends up in error:

2018-08-28 10:33:12 Connection: Failed to connect to server. Error number 2. "Error notice: stream_socket_client(): unable to connect to ssl://mail.xyz.com:465 (Connection refused)
2018-08-28 10:33:12 SMTP ERROR: Failed to connect to server: Connection refused (111)

Here, this “Connection Refused” error means that sending mail server refuses outbound connections on port 465 and is not able to connect to remote mail server.

3. Incorrect settings in PHPMailer

This SMTP error can also happen if the mail server name is incorrectly set (with additional white space) in PHPMailer configuration. Then, web form tries to connect to an invalid name and fails.

4. DNS failures

For the PHPMailer to work properly, the mail server specified in its configuration should have proper dns records. When dns do not work on the server, a look up from the server shows wrong IP address or no IP address for the mail server. Again, that causes mail to fail with SMTP error.

How to fix SMTP Error: Failed to connect to server

For mails to work with PHPMailer, both sending and receiving server has to accept connections.

Our Support Engineers primarily checks the connection between mail servers and find whether it is an incoming or outgoing block.

Then, to fix the mail error, we make changes on the server that includes the following :

  1. Modify the firewall rules on the server to allow outbound connections on ports like 465.
  2. Modify the SMTP restrictions on the server. Then, add particular website user to the list of users who can make outbound SMTP connections.
  3. Edit PHPMailer settings like Host, Port etc.
  4. Correct DNS resolution for mail server.

Conclusion

“SMTP ERROR: Failed to connect to server” mainly happens because of mail server connectivity issues, wrong port settings etc. Here, we have discussed the causes that our Support Engineers often see in servers and how we fix them.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Hi,

Last week, PHPMailer suddenly stopped working. I got the following as the error message when I send the test e-mail:

SMTP -> ERROR: Failed to connect to server: Connection timed out (110)
SMTP Error: Could not connect to SMTP host.

I’ve found the same issue with the module SMTP Authentication Support.

Any idea what could have caused this? Any good suggestions for debugging this?

Tag1 supports the Drupal Project.Tag1 logo

Comments

smk-ka’s picture

Connection time-out means the mail server cannot be reached anymore. If the mail server is different from your web server (i.e. not localhost) I’d check with your hosting provider whether they enabled some sort of firewall that blocks connections on the SMTP port (port 25 usually).

  • Log in or register to post comments

Relia’s picture

Hello I have the same problem.

I set up PHPMailer to send mails trought gmail:

Primary SMTP server:mail.gbt.tfo.upm.es
SMTP Port: 465
Use secure protocol: SSL

User: usergmail@gmail.com
password: gmailpassword

TEst configuration: mailtutest@domain.com

But when I submit clickin save configuration, the next error message appear:

A test e-mail has been sent to fjpeces@gfgf.es. You may want to check the logs for any error messages.
SMTP -> ERROR: Failed to connect to server: Connection timed out (110)
SMTP Error: Could not connect to SMTP host.

I’m using OpenSuSe 10.3, Server Apache2, php 5.2.5.

I think the problem is the ports are closed to outside, but before to communicate with the admin, i’d want read your opinions!

thanks!

  • Log in or register to post comments

LEternity’s picture

I contacted my provider and they fixed the problem. I.e. they screwed up…

  • Log in or register to post comments

Relia’s picture

i fixed the problem, I cotacted admin and the problem was the ports! They are closed!

  • Log in or register to post comments

smk-ka’s picture

Thanks for your feedback, I’ve added a description for this error to README.txt, based on what I said in #1.

  • Log in or register to post comments
Status: Fixed » Closed (fixed)

Automatically closed — issue fixed for 2 weeks with no activity.

  • Log in or register to post comments

ThirstySix’s picture

In localhost SMTP work’s fine, but , site it does not work SMTP.
I give same configuration in SMTP localhost and site.

but I get below error

SMTP -> ERROR: Failed to connect to server: Connection timed out (111)
SMTP Error: Could not connect to SMTP host. 

I changed port number and name….etc..
but i get same error….
how can I slove this?

Thanks in advance..

  • Log in or register to post comments

smk-ka’s picture

@satheeshkumarr Read comment #1. Contact your hosting provider to open specific firewall ports.

  • Log in or register to post comments

Mahadirz’s picture

Version: 6.x-2.1 » 7.x-3.x-dev
Component: Code » Miscellaneous
Status: Closed (fixed) » Active

I also got this same problem before…
Try checking all your files and directories permission. If all your files and folder permission is set to 777 they can’t access to SMTP config.

So reset the permission of all the files to 644 while the folders to 755 .

cheers…
http://www.mahadirlab.com/en

  • Log in or register to post comments

zabalex’s picture

I had the same issue with my host. They told me to try every possible option, stated that it was a problem with my code, email server, application (drupal), etc.
I wasted 2 weeks, than hired a guy to develop firewall ports blocking detection application, and here it is. As soon as I was able to proove to hosting company that they blocked port 465, they did not admin problem. As soon as I showed them this tool, yes, they admitted that they have problem and opened the port.
Here is the tool: Port forwarding tester external server:

Let me know what you think

  • Log in or register to post comments

earth1’s picture

@smk-ka #1. I am using PHPMailer 6.x-2.2. Firewall is not the answer.

error -> SMTP error: could not connect to SMTP host.

The website is using godaddy with jangosmtp as it email system. It’s Primary SMTP server: relay.jangostmp.net and SMTP port: 587. The godaddy representative said go to my MX (Mail Exchanger) and set relay.jangostmp.net. But this didn’t work. I am running out of ideas. Can you help me?

Thanks in advance

  • Log in or register to post comments

zabalex’s picture

I spent so much time on issues like that, I might be able to help you Earth1 if the tool from my previous post doesn’t show port as blocked.
Don’t trust their advise on MX Exchanger. I prooved back to GoDaddy that over 50% of popular organizations don’t set their relays, and their emails still go through fine.
What is your domain? Send me PM if you don’t want to list it here.

  • Log in or register to post comments

keithm’s picture

This problem may be a result of enabling IPv6 support in the operating system. I saw several sites with working PHPMailer configurations break when my host enabled IPv6. PHP has multiple known bugs in dealing with IPv6.

PHPMailer uses the PHP fsockopen() function that has this known bug.

The problem is that fsockopen() doesn’t detect that a connection was actively refused and instead times out on it.

The problem scenario occurs when the host has both ipv4 and ipv6 addresses (e.g,, smtp.gmail.com), the service is only listening on ipv4 but ipv6 has precedence, which results in:

  1. trying IPv6
  2. time out
  3. fail

instead of:

  1. trying IPv6
  2. connection refused
  3. trying IPv4
  4. success

If this is the problem, you can work around it by setting the IP address directly in the PHPMailer settings or in /etc/hosts. The problem still exists (at least) in PHP v5.3.2.

  • Log in or register to post comments

vvenk’s picture

Hi:

I am on a Windows 7 machine and developing an application that has SendEmail as a function using VB.Net and MS Visual Studio 2010.

The code works fine on another Windows 7 machine. The only difference is that the laptop it does not work is a corporate laptop and I am part of the Administrators group on that laptop.

I used the tool and it says the port is open.

Any idea how to resolve the issue?

venki

  • Log in or register to post comments

ravi_dev’s picture

I have another mail server for my site then how can i connect ‘@fsockopen(«www.google.com», 80, $errno, $errstr, 10)’?

  • Log in or register to post comments

Anonymous’s picture

Comment #16

Anonymous (not verified) CreditAttribution: Anonymous commented 7 October 2016 at 08:14

This error is not resolving check the image after saving smtp configuration this screen appears

  • Log in or register to post comments

oadaeh’s picture

Comment #17

oadaeh CreditAttribution: oadaeh as a volunteer commented 7 October 2016 at 13:21

Status: Active » Closed (won’t fix)

@saif-ur-rehman, that error is not from this module, but from the Variable module. You need to start there to resolve the problem. And next time, open a new issue, as this one you posted on is unrelated.

  • Log in or register to post comments

oadaeh’s picture

Comment #18

oadaeh CreditAttribution: oadaeh as a volunteer commented 7 October 2016 at 13:25

@saif-ur-rehman, allow me to clarify what I said about starting a new issue. What you did in searching for an existing issue to post in was a good thing, but the issue you ended up posting in was unrelated to your problem, and so you should have just created a new issue.

  • Log in or register to post comments

oadaeh’s picture

Comment #19

oadaeh CreditAttribution: oadaeh as a volunteer commented 7 October 2016 at 13:26

Status: Closed (won’t fix) » Fixed

I set the wrong status previously, so now I’m fixing that.

  • Log in or register to post comments

oadaeh’s picture

Comment #20

oadaeh CreditAttribution: oadaeh as a volunteer commented 7 October 2016 at 13:26

Status: Fixed » Closed (fixed)
  • Log in or register to post comments

thanhseouc’s picture

My site is not a bug fix as above not overcome

  • Log in or register to post comments

oadaeh’s picture

  • Log in or register to post comments

BloggerLive login mailbox verificationWhen I met this error, I checked this article compared to this article.Click to view
but not solved


solve

Local: Comment$mail->SMTPSecure = ‘ssl’ This item, and setmail->Port = 25 Port25


online :: Open$mail->SMTPSecure = ‘ssl’ This item, and setmail->Port = 465 Port465


Post function

*Send email method
 *@param $to: Receiver $title: Title $content:content of email 
 *@return bool true:Sent successfully  false:Failed to send 
 */
function sendMail($to,$title,$content){
    // Introduced the core file of PHPMAiler to use Require_Once to include a warning that avoids repayment definitions of PHPMAiler class
    require_once("./PHPMailer_5.2.2/class.phpmailer.php"); 
    require_once("./PHPMailer_5.2.2/class.smtp.php");
    $mail = new PHPMailer();// Institute instantiate the PHPMAILER core class
     $mail->SMTPDebug = 1;/ / Whether to enable SMTP Debug for debugging development Environment, it is recommended to turn off the Debug debugging mode by default to the production environment comment.
    $mail->isSMTP();// Send an email using SMTP authentication
    $mail->SMTPAuth=true;// SMTP requires authentication this must be True
    $mail->Host = 'smtp.qq.com';// Link the server address of the QQ domain mailbox
    // $ mail-> SMTPSecure = 'ssl'; // Setting Using SSL Encryption Method to log in
    $mail->Port = 25;// Set the SSL to connect the remote server port number of the SMTP server, the previous default is 25, but now the new seems to be available 465 or 587
    $mail->CharSet = 'UTF-8';/ / Set the encoded encoding of the message to choose GB2312 I like UTF-8 It is said that UTF8 will be garbled under certain clients.
    $mail->FromName = 'welcome';// Set the sender's name (nickname) arbitrarily, display the sender's name before the sender of the recipient mail
    $mail->Username ='[email protected]';// SMTP login account here to fill in the QQ number of the string format
    $mail->Password = '*******';// SMTP login password uses the generated authorization code (just told you to save the latest authorization code) [very important: After logging in to the mailbox, go to get this authorization code in the settings]
    $mail->From = '[email protected]';/ / Set the sender email address here to fill in the "sender mailbox" mentioned above
    $mail->isHTML(true);// message body is HTML encoding Note Any method is no longer attribute true or false
    $mail->addAddress($to);/ / Set the recipient email address
    $mail->Subject = $title;// Add the subject of the message
    $mail->Body = $content;/ / Add ISHTML to TRUE, and you can be a complete HTML string such as: read the local HTML file using the file_get_contents function.
    // Simple judgment and prompt information
    if($mail->send()) {
        return true;
    }else{
        return false;
    }
}

Проблема — скорее две несвязанные проблемы — то, что вы испытываете, довольно проста:

ОШИБКА SMTP: Не удалось подключиться к серверу: время ожидания подключения (110) Ошибка SMTP connect().

и вы подтвердили, что сервер действительно принимает соединения:

Я попытался подключиться к SMTP-серверу с помощью команды telnet

Last login: Fri Sep 16 11:08:06 on ttys000
admin:~ admin$ telnet mail.example.in 25
Trying 111.91.153.112...
Connected to mail.example.in.

Ваш script не может подключиться к SMTP-серверу при запуске с его производственного сервера.

Вероятная причина заключается в том, что сервер производства имеет брандмауэр, который во избежание злоупотреблений предотвращает любое подключение к внешней стороне. Сервер может обслуживать веб-запросы, но не более.

Если ваш тест подтвердил, что порт 25 не отвечает, то (после проверки правильности адреса хоста) вы могли бы попробовать telnet mail.example.in 587 вместо. Если это сработало, это могло означать, что сервер не принимает небезопасные соединения (порт 25), но принимает безопасные соединения. С помощью PHPMailer вы могли бы попробовать активировать безопасное соединение:

$mail->SMTPSecure = 'tls';

или

$mail->SMTPSecure = 'ssl';

Если это не сработает, у вас может быть проблема с брандмауэром; или вам может потребоваться посмотреть phpinfo() и убедиться, что у вас есть поддержка OpenSSL, доступная в PHP.

Что вам нужно сделать

  • попросите ИТ-специалистов, которые поддерживают производственный сервер, открыть брандмауэр;
  • более перспективно, спросите их, как отправлять электронные письма с этого сервера. Скорее всего, вам нужно использовать функцию mail() или использовать localhost или 127.0.0.1 как SMTP-сервер. Затем электронные письма будут отправляться через вашу сервисную сеть вашего производственного сервера.

Они могут сказать вам, что порт 25 не разрешен, но разрешен порт (скажем) 465 или 567. Вам необходимо будет обновить свою конфигурацию и/или добавить TLS/SSL соответственно (см. Выше).

  • или вам может быть позволено подключиться к стороннему SMTP-серверу, которому вы должны будете предоставить IP-адрес, чтобы позволить ИТ-ребятам открыть соответствующее окно брандмауэра. Затем электронные письма будут отправляться через сторонний сервер.

Вторая проблема (возможно, НЕ проблема)

250 [email protected] Отправитель OK RCPT: [email protected] 554 Реле отклонено по политическим причинам.

Кроме того, чтобы избежать злоупотреблений, SMTP-серверы не позволят каждому подключаться и отправлять электронные письма, но только их собственные клиенты. Я вижу, что в конфигурации PHPMailer вы указали пользователя и пароль. В сеансе telnet вы этого не сделали. Поэтому вполне возможно, что PHPmailer может отправлять, но не подключаться, в то время как ваш telnet может подключаться, но не отправлять.

Как только вы решите проблему подключения, проблема аутентификации будет решена или исчезнет (потому что вы будете использовать другой сервер, предоставленный вам ИТ-ребятами, например localhost).

Третья проблема (может никогда не возникнуть)

Третий способ злоупотребления услугами — чрезмерное использование — отправка слишком большого количества сообщений электронной почты слишком многим людям. Проверьте с ИТ-ребятами, какие приемлемые политики предназначены для отправки писем.

Проблемы, проблемы

Другие вещи, на которые нужно обратить внимание, — это достоверность источника (вы можете отправить электронные письма от имени какого-либо домена, который не определил ваш SMTP-сервер в качестве разрешенного отправителя) и конфиденциальность данных (даже с TLS/SSL, если вам предоставлен localhost в качестве SMTP-сервера, ваши ИТ-ребята будут иметь полный, неограниченный, необнаруживаемый доступ к любому отправляемому вами электронному адресу. Возможно, вы можете или не можете быть в порядке).

Понравилась статья? Поделить с друзьями:
  • Ошибка smtp error the following recipients failed
  • Ошибка smg019 man of medan
  • Ошибка smart жесткого диска вылечить
  • Ошибка suspension fault ситроен с5
  • Ошибка smart status bad backup and replace как исправить