Smtp error failed to connect to server connection timed out 110 phpmailer

I am getting SMTP Error with PHP Mailer and Outlook SMTP. I am confused here because it is working fine on localhost with Port number 25 but It is not working on Hosting Server, I have tried all po...

I am getting SMTP Error with PHP Mailer and Outlook SMTP. I am confused here because it is working fine on localhost with Port number 25 but It is not working on Hosting Server, I have tried all ports with SSL & TLS.

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

My Code:

<?php

include("PHPMailer.php"); 

error_reporting(E_ALL);
ini_set('display_errors', '1');

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp.live.com";
$mail->SMTPDebug = 2;
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = "info@neelcomputech.com";
$mail->Password = "password";
$mail->Priority    = 1;
$mail->CharSet     = 'UTF-8';
$mail->ContentType = 'text/html; charset=utf-8rn';

$mail->From = "info@neelcomputech.com";
$mail->FromName = $name;
$mail->AddAddress("info@neelcomputech.com");

$mail->IsHTML(true);

$mail->Subject = "You got Message from Website";
$mail->Body = "testing";

if(!$mail->Send())
{
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else
{
    echo 'success';
}

?>

Please help me to solve this issue. I have Shared Linux Hosting.

mujuonly's user avatar

mujuonly

10.6k5 gold badges44 silver badges75 bronze badges

asked May 21, 2014 at 12:06

Jeeten Parmar's user avatar

Jeeten ParmarJeeten Parmar

5,34015 gold badges60 silver badges110 bronze badges

6

I had a similar problem, and it turned out my host (Bluehost) blocked outgoing connections on port 465. I will post the solution here in the hope that helps you. But I’m not expert enough to know if it’s the same problem or not.

I found a wonderful how-to which fixed it for me:

  1. In your cPanel DNS Zone editor, find the MX (Mail Exchanger) section, and select ‘remote mail exchanger’.
  2. In the cPanel email accounts section, create the appropriate email address (don’t skip this)
  3. Don’t use «smtp.live.com» as your smtp host. Use the smtp host of your Shared Linux Hosting smtp. I don’t know how you will get yours. Mine is boxXXXX.bluehost.com.
  4. Set your username and password to be the same as the email account you just set-up in cPanel.

answered Jul 5, 2014 at 4:26

Kit Johnson's user avatar

1

None of the answers worked for me.
After many hours, I found the problem, but only works for Cpanel/WHM

  • Login into WHM.
  • Go to ConfigServer Security & Firewall inside plugins option.
  • Click on Firewall configuration
  • Filter by SMTP Settings
  • Look for SMTP_ALLOWUSER option and add the Cpanel account’s username separated by coma
  • Restart the Firewall.

If you don’t have access to WHM ask your provider.

Hope it helps!

answered May 4, 2016 at 21:23

Juan Angel's user avatar

Juan AngelJuan Angel

6286 silver badges6 bronze badges

My code is correct.
The issue was with Hosting Provider. I contacted them about this and they did some configuration on their Server and it’s done.

answered Sep 8, 2017 at 5:38

Jeeten Parmar's user avatar

Jeeten ParmarJeeten Parmar

5,34015 gold badges60 silver badges110 bronze badges

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

I am getting SMTP Error with PHP Mailer and Outlook SMTP. I am confused here because it is working fine on localhost with Port number 25 but It is not working on Hosting Server, I have tried all ports with SSL & TLS.

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

My Code:

<?php

include("PHPMailer.php"); 

error_reporting(E_ALL);
ini_set('display_errors', '1');

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp.live.com";
$mail->SMTPDebug = 2;
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = "info@neelcomputech.com";
$mail->Password = "password";
$mail->Priority    = 1;
$mail->CharSet     = 'UTF-8';
$mail->ContentType = 'text/html; charset=utf-8rn';

$mail->From = "info@neelcomputech.com";
$mail->FromName = $name;
$mail->AddAddress("info@neelcomputech.com");

$mail->IsHTML(true);

$mail->Subject = "You got Message from Website";
$mail->Body = "testing";

if(!$mail->Send())
{
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else
{
    echo 'success';
}

?>

Please help me to solve this issue. I have Shared Linux Hosting.

mujuonly's user avatar

mujuonly

10.6k5 gold badges44 silver badges75 bronze badges

asked May 21, 2014 at 12:06

Jeeten Parmar's user avatar

Jeeten ParmarJeeten Parmar

5,34015 gold badges60 silver badges110 bronze badges

6

I had a similar problem, and it turned out my host (Bluehost) blocked outgoing connections on port 465. I will post the solution here in the hope that helps you. But I’m not expert enough to know if it’s the same problem or not.

I found a wonderful how-to which fixed it for me:

  1. In your cPanel DNS Zone editor, find the MX (Mail Exchanger) section, and select ‘remote mail exchanger’.
  2. In the cPanel email accounts section, create the appropriate email address (don’t skip this)
  3. Don’t use «smtp.live.com» as your smtp host. Use the smtp host of your Shared Linux Hosting smtp. I don’t know how you will get yours. Mine is boxXXXX.bluehost.com.
  4. Set your username and password to be the same as the email account you just set-up in cPanel.

answered Jul 5, 2014 at 4:26

Kit Johnson's user avatar

1

None of the answers worked for me.
After many hours, I found the problem, but only works for Cpanel/WHM

  • Login into WHM.
  • Go to ConfigServer Security & Firewall inside plugins option.
  • Click on Firewall configuration
  • Filter by SMTP Settings
  • Look for SMTP_ALLOWUSER option and add the Cpanel account’s username separated by coma
  • Restart the Firewall.

If you don’t have access to WHM ask your provider.

Hope it helps!

answered May 4, 2016 at 21:23

Juan Angel's user avatar

Juan AngelJuan Angel

6286 silver badges6 bronze badges

My code is correct.
The issue was with Hosting Provider. I contacted them about this and they did some configuration on their Server and it’s done.

answered Sep 8, 2017 at 5:38

Jeeten Parmar's user avatar

Jeeten ParmarJeeten Parmar

5,34015 gold badges60 silver badges110 bronze badges

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»;

Содержание

  1. SMTP ERROR: Failed to connect to server: Connection timed out (110) SMTP connect() failed. #1216
  2. Comments
  3. Debug output
  4. Problem description
  5. Code to reproduce
  6. Debug output
  7. SMTP ERROR: Failed to connect to server: Connection timed out (110) SMTP connect() failed. part#5 #1221
  8. Comments
  9. “Smtp error: Failed to connect to server” – Causes and Fixes
  10. What is “Smtp error: Failed to connect to server” ?
  11. What causes SMTP ERROR: Failed to connect to server ?
  12. 1. SMTP restrictions on the server.
  13. 2. Firewall restrictions on the server
  14. 3. Incorrect settings in PHPMailer
  15. 4. DNS failures
  16. How to fix SMTP Error: Failed to connect to server
  17. Conclusion
  18. PREVENT YOUR SERVER FROM CRASHING!
  19. 8 Comments

SMTP ERROR: Failed to connect to server: Connection timed out (110) SMTP connect() failed. #1216

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

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.

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

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.

The text was updated successfully, but these errors were encountered:

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.

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

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.

The above is the configuration recommended by vodahost:

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

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 ?

Источник

SMTP ERROR: Failed to connect to server: Connection timed out (110) SMTP connect() failed. part#5 #1221

Hello Mr Bointon,

Hosting provider vodahost has sent me the following information:

It seems that the reported trouble is isolated with your PHP mailer script. I created a smaple test mail script and was able to successfully execute it. You can verify this from the screenshot below. You can edit the script and test with your mail address to verify the working of PHP mailer function.

Can you please check this with your developer and see if there is any parameter included in the scripts is causing this trouble.

Feel free to contact us for assistance.

Basically this test.php has the following code:

They are using the mail function of php to send the email and it seems to be passing without problem (even though it fell on my hotmail spam folder).

Thank you so much.
Regards
Jose

The text was updated successfully, but these errors were encountered:

It’s fine that it works for them, but that doesn’t tell you anything about whether it works on your server, which is where networking restrictions will apply. Using the mail function means that it’s sending via your local mail server (and not using SMTP directly at all), which on a shared hosting service is likely to relay through your ISP’s mail servers which are probably exempt from network filters, so that’s useless as a diagnostic tool. Here is a simple test script:

You should get output like this:

If you still get a timeout, you definitely have a network problem that no amount of messing with your scripts can fix.

Yes, it’s a problem with your server, not your local wifi or internet connection. It goes like this:

The problem is on that last hop, between your server and the mail server. I expect this is an outbound firewall block on your server’s network. The mail server may not block inbound connections from anywhere, which is why voda4’s own tests (and mine) are working.

That said, I just spotted that both voda4.vodahost4.com and www.crmpt.com point at the same IP address, so connecting to voda4.vodahost4.com is the same as connecting to localhost . In that test script, try changing the fsockopen line to:

That should not have any firewall issues, and does not need any encryption. It’s essentially the same as using mail() , but it’s safer and faster. It may still end up in spam, but that’s a separate problem.

Did as you told me to and there was a different message now.

http://www.crmpt.com/test2.php
Could I please ask you to have a look at the message ?

RESULT:
220 gamma.vodahost.com ESMTP Postfix 221 2.0.0 Bye

as a side note, I would like to add that I’ve always used and am using localhost as my server in all phpmailer scripts, which are some tenths all over my routines.

Also changed to localhost the server on the.
Also changed the variables:

http://www.crmpt.com/email_test_send_new.php
Could I please ask you to have a look at the message ?

Any ideas ?
Thank you in advance for all the help.

The connection is working, but it’s asking you to authenticate (which is pretty pointless on localhost, but whatever!), so set:

Thank you for your reply.

Those 1+2 lines have been there from the start and I am pretty sure they are both correct, because I have this email (also) installed in Microsoft outlook sending and receiving.

Sent folder in outlook:

Receive folder in hotmal:

Still no light in the end of the tunnel ?

Thank you again and again.
Jose

Ah, looking at the output more carefully, it doesn’t actually offer authentication, so set $mail->SMTPAuth = false;

2017-11-02 14:34:28 Connection: opening to localhost:25, timeout=300, options=array()
2017-11-02 14:34:28 Connection: opened
2017-11-02 14:34:29 SERVER -> CLIENT: 220 gamma.vodahost.com ESMTP Postfix
2017-11-02 14:34:29 CLIENT -> SERVER: EHLO www.crmpt.com
2017-11-02 14:34:29 SERVER -> CLIENT: 250-gamma.vodahost.com250-PIPELINING250-SIZE 10240000250-VRFY250-ETRN250-ENHANCEDSTATUSCODES250-8BITMIME250 DSN
2017-11-02 14:34:29 CLIENT -> SERVER: MAIL FROM:2e@afaturar.com
2017-11-02 14:34:29 SERVER -> CLIENT: 250 2.1.0 Ok
2017-11-02 14:34:29 CLIENT -> SERVER: RCPT TO:ca@mz2e.com
2017-11-02 14:34:29 SERVER -> CLIENT: 250 2.1.5 Ok
2017-11-02 14:34:29 CLIENT -> SERVER: RCPT TO:jose.jc.almeida@hotmail.com
2017-11-02 14:34:29 SERVER -> CLIENT: 250 2.1.5 Ok
2017-11-02 14:34:29 CLIENT -> SERVER: RCPT TO:jose.jc.almeida@gmail.com
2017-11-02 14:34:29 SERVER -> CLIENT: 250 2.1.5 Ok
2017-11-02 14:34:29 CLIENT -> SERVER: DATA
2017-11-02 14:34:29 SERVER -> CLIENT: 354 End data with .
2017-11-02 14:34:29 CLIENT -> SERVER: Date: Thu, 2 Nov 2017 14:34:28 +0000
2017-11-02 14:34:29 CLIENT -> SERVER: To: ca@mz2e.com
2017-11-02 14:34:29 CLIENT -> SERVER: From: 2e@afaturar.com
2017-11-02 14:34:29 CLIENT -> SERVER: Cc: jose.jc.almeida@hotmail.com
2017-11-02 14:34:29 CLIENT -> SERVER: Reply-To: 2e@afaturar.com
2017-11-02 14:34:29 CLIENT -> SERVER: Subject: EMAIL TEST
2017-11-02 14:34:29 CLIENT -> SERVER: Message-ID: Elc5pIVvjnPyZ4vrxAN5h15kamqjQcsPnyGlKcDqY@www.crmpt.com
2017-11-02 14:34:29 CLIENT -> SERVER: X-Mailer: PHPMailer 6.0.1 (https://github.com/PHPMailer/PHPMailer)
2017-11-02 14:34:29 CLIENT -> SERVER: MIME-Version: 1.0
2017-11-02 14:34:29 CLIENT -> SERVER: Content-Type: multipart/alternative;
2017-11-02 14:34:29 CLIENT -> SERVER: boundary=»b1_Elc5pIVvjnPyZ4vrxAN5h15kamqjQcsPnyGlKcDqY»
2017-11-02 14:34:29 CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
2017-11-02 14:34:29 CLIENT -> SERVER:
2017-11-02 14:34:29 CLIENT -> SERVER: This is a multi-part message in MIME format.
2017-11-02 14:34:29 CLIENT -> SERVER: —b1_Elc5pIVvjnPyZ4vrxAN5h15kamqjQcsPnyGlKcDqY
2017-11-02 14:34:29 CLIENT -> SERVER: Content-Type: text/plain; charset=us-ascii
2017-11-02 14:34:29 CLIENT -> SERVER:
2017-11-02 14:34:29 CLIENT -> SERVER: EMAIL TEST ** EMAIL TEST ** EMAIL TEST **
2017-11-02 14:34:29 CLIENT -> SERVER:
2017-11-02 14:34:29 CLIENT -> SERVER: —b1_Elc5pIVvjnPyZ4vrxAN5h15kamqjQcsPnyGlKcDqY
2017-11-02 14:34:29 CLIENT -> SERVER: Content-Type: text/html; charset=us-ascii
2017-11-02 14:34:29 CLIENT -> SERVER:
2017-11-02 14:34:29 CLIENT -> SERVER: EMAIL TEST ** EMAIL TEST ** EMAIL TEST **
2017-11-02 14:34:29 CLIENT -> SERVER:
2017-11-02 14:34:29 CLIENT -> SERVER:
2017-11-02 14:34:29 CLIENT -> SERVER: —b1_Elc5pIVvjnPyZ4vrxAN5h15kamqjQcsPnyGlKcDqY—
2017-11-02 14:34:29 CLIENT -> SERVER:
2017-11-02 14:34:29 CLIENT -> SERVER: .
2017-11-02 14:34:29 SERVER -> CLIENT: 250 2.0.0 Ok: queued as 307D6120B45
2017-11-02 14:34:29 CLIENT -> SERVER: QUIT
2017-11-02 14:34:29 SERVER -> CLIENT: 221 2.0.0 Bye
2017-11-02 14:34:29 Connection: closed

Good, it’s working.

Should the emails not arrive to the recipients ?

Yes, but that’s outside the control of your script. To see what happens to messages after this you would need to look in your mail server logs, probably somewhere like /var/log/mail.log . if you can’t look at them, you need to ask your support service.

Trust you are well?

Now there is another problem arising that is, because I has to remove SMTP Authentication from my phpmailer scripts to make my emails function again, now I have received the foloowing email from Mail Delivery System MAILER-DAEMON@gamma.vodahost.com:

I’m sorry to have to inform you that your message could not be delivered to one or more recipients. It’s attached below.

For further assistance, please send mail to postmaster.

If you do so, please include this problem report. You can delete your own text from the attached returned message.

jose.jc.almeida@gmail.com: host gmail-smtp-in.l.google.com[74.125.29.27]
said: 550-5.7.1 This message does not have authentication information or
fails to pass 550-5.7.1 authentication checks. To best protect our users
from spam, the 550-5.7.1 message has been blocked. Please visit 550-5.7.1
https://support.google.com/mail/answer/81126#authentication for more 550
5.7.1 information. b29si1213791qte.461 — gsmtp (in reply to end of DATA
command)

GMAIL does not accept my emails, and we all know how many people use GMAIL as its personal email.

How do I turnaround this problem ?
If I change againg SMTPAuth=true, then it will not connect.

It is strange because have been working with phpmailer in vodahost servers maybe for 10 years (or more) now and never had any problem with my phpmailer scripts.

Something must have changed from their side, because this all started to happen suddenly, but they do not seem to find what happened in the first place.

I am on a dead end.

SMTPauth = True, won’t connect
SMTPauth = False, will loose the chance to send emails to gmail addresses.

IS there any pertinent info we can retrieve from Gmail’s message ?

Источник

“Smtp error: Failed to connect to server” – Causes and Fixes

by Sijin George | Mar 1, 2019

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 :

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:

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:

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.

I want to send an email through SMTP. But its not sending due to some error.

Hello Ashiq,
Can you please share the SMTP error that you are getting? If you need help, we’ll be happy to talk to you on chat (click on the icon at right-bottom).

I keep getting this error on hostinger hpanel, but when i use namecheap, it worked:

I keep getting this error on hostinger hpanel, but when i use namecheap, it worked:

I m also getting “failed to connect (101)” . it was working fine on local server but when I uploaded my Website it is no longer working. Please help

If you still face the issue, We’ll be happy to talk to you on chat (click on the icon at right-bottom). We need to look into the details of the error.

get smtp error I configure all settings accurately fine but its not working

Versions:
WordPress: 5.9.2
WordPress MS: No
PHP: 7.3.33
WP Mail SMTP: 3.3.0

Params:
Mailer: smtp
Constants: No
ErrorInfo: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Host: mail.ekotees.com
Port: 465
SMTPSecure: ssl
SMTPAutoTLS: bool(true)
SMTPAuth: bool(true)

Server:
OpenSSL: OpenSSL 1.1.1d 10 Sep 2019
Apache.mod_security: No

SMTP Debug:
2022-03-14 06:40:20 Connection: opening to ssl://mail.ekotees.com:465, timeout=300, options=array()

2022-03-14 06:40:20 Connection failed. Error #2: stream_socket_client(): Peer certificate CN=`rumi.corpservers.net’ did not match expected CN=`mail.ekotees.com’ [/home/ekoteesc/public_html/wp-includes/PHPMailer/SMTP.php line 388]

2022-03-14 06:40:20 Connection failed. Error #2: stream_socket_client(): Failed to enable crypto [/home/ekoteesc/public_html/wp-includes/PHPMailer/SMTP.php line 388]

2022-03-14 06:40:20 Connection failed. Error #2: stream_socket_client(): unable to connect to ssl://mail.ekotees.com:465 (Unknown error) [/home/ekoteesc/public_html/wp-includes/PHPMailer/SMTP.php line 388]

2022-03-14 06:40:20 SMTP ERROR: Failed to connect to server: (0)

Our Experts can help you with the issue, we’ll be happy to talk to you on chat

Источник

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

296 Upvotes | 34 comments

The author voluntarily contributed this tutorial as a part of Pepipost Write to Contribute program.

Introduction

Facing an error which says «PHPMailer SMTP Error: Could not connect to SMTP host»?

Let’s solve it together.

PHPMailer is one of the most popular open-source written in PHP for sending emails. While it’s easy to deploy and start sending emails, but there is a common error which most of us might be facing.

In this document, I have tried sharing the answer for some of the most occurring errors with the PHPMailer:

#Error: PHPMailer: SMTP Error: Could Not Connect To SMTP Host

Depending on your situation, there can be multiple reasons for the occurrence of this error. So, please try to go through the different scenarios below and pick the one which is closest to your use case.

Possible Problem 1: Problem With The Latest Version Of PHP

I tried using PHPMailer in many projects in the past and it worked buttery smooth. But, when I updated the PHP version to 5.6, I started getting an SMTP connection error. Later, I observed that this problem is there with the latest version of the PHP.

I noticed that in the newer version, PHP has implemented stricter SSL behaviour which has caused this problem.

Here is a help doc on PHPMailer wiki which has a section around this.

And, here is the quick workaround mentioned in the above wiki, which will help you fix this problem:

$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);

You can also change these settings globally, in the php.ini file but that’s a really bad idea because PHP has done these SSL level strictness for very good reasons only.

This solution should work fine with PHPMailer v5.2.10 and higher.

Possible Problem 2: Using Godaddy As The Hosting Provider

If you are running your code on Godaddy and trying to connect to some third-party SMTP provider like smtp.pepipost.com or smtp.sendgrid.com and getting some errors like this;

Mailer Error: SMTP connect() failed.

then nothing to really debug further, because it is because of a wried rule imposed by Godaddy on its user, where Godaddy has explicitly blocked the outgoing SMTP connection to ports 25, 587 and 465 to all external servers except for their own. Godaddy primarily wants their users to use their own SMTP instead of any third party SMTP, which is not at all an acceptable move for the developer community and many have has expressed their frustration in form of issues on StackOverflow too.

Your PHPmailer code might work perfectly fine on a local machine but the same code, when deployed on Godaddy server might not work and that’s all because of this silly rule implemented by Godaddy.

Here are few workarounds to avoid SMTP connection issues in Godaddy:

#1- Use Godaddy SMTP Instead Of Any Third Party:

In case you are sending 1-1 personalized emails, then using Godaddy SMTP makes sense. For that, just make the following changes in your PHPMailer code and you will be done;

$mail->isSMTP();
$mail->Host = 'localhost';
$mail->SMTPAuth = false;
$mail->SMTPAutoTLS = false; 
$mail->Port = 25; 

Note: Godaddy also restricts using any free domains like gmail, yahoo, hotmail, outlook, live, aim or msn as sender domain/From address. This is mostly because these domains have their own SPF and DKIM policies and some one can really forg the from address if allowed without having custom SPF and DKIM.

But, in case you want to send bulk/emails at scale then it becomes a bottleneck with high chances of your emails been landed in spam and your domain/IP address getting blacklisted. In such a case, I would suggest checking your email blacklist status and going with an option no #2.

#2- Use Email APIs Instead Of Any SMTP:

Godaddy can block the outgoing SMTP ports but can’t really block the outgoing HTTP ports (80, 8080) 😀 So, I would recommend using some good third party email service provider who provides email APIs to send emails. Most of these providers have code libraries/SDKs like PHPMailer which you can install and include in your code to start sending emails. Unlike using Godaddy’s local SMTP, using email APIs will give you a better control on your email deliverability.

Possible Problem 3: Getting SMTP Connection Failure On A Shared Hosting Provider

If you are running your code on a shared hosting provider and trying to connect to some third-party SMTP provider like smtp.pepipost.com or smtp.sendgrid.com and getting some errors like this;

SMTP connect() failed.

then, this is mostly because of the firewall rules on their infrastructure which explicitly blocks the outgoing SMTP connection to ports 25, 587 and 465 to all external servers. This rule is primarily to protect the infrastructure from sending spam, but also a really frustrating situation for developers like us.

The only solution to this is, same as I suggested above in the Godaddy section (Use Email APIs instead of any SMTP) or contact the hosting provider to allow connection to SMTP ports.

How to check whether your outgoing port (25, 587 or 465) is really blocked or not?

1. Trying doing telnet
Using telnet command you can actually test whether the port is opened or not.

//Type the following command to see if Port 25 is blocked on your network. 
telnet pepipost.com 25

If Port 25 is not blocked, you will get a successful 220 response (text may vary).

Trying 202.162.247.93... 
Connected to pepipost.com. 
Escape character is '^]'. 
220 pepipost.com ESMTP Postfix

If Port 25 is blocked, you will get a connection error or no response at all.

Trying 202.162.247.93...
telnet: connect to address 202.162.247.93: Connection refused
telnet: Unable to connect to remote host

2. Use outPorts
outPorts is a very good open-source on GitHub to which scans all your ports and gives the result.
Once outPorts is installed, you can type the following command in the terminal to check port 25 connectivity:
outPorts 25

Possible Problem 4: SELinux Blocking Issue

In case you are some error like the following:

SMTP -> ERROR: Failed to connect to server: Permission denied (13)

then, the most probably your SELinux is preventing PHP or the webserver from sending emails.

This problem is mostly with Linux based machines like RedHat, Fedora, Centos, etc.

How to debug whether it’s really the SELinux issue which is blocking these SMTP connections?

You can use the getsebool command to check whether the httpd daemon is allowed to make an SMTP connection over the network to send an email.

getsebool httpd_can_sendmail
getsebool httpd_can_network_connect

This command will return a boolean on or off. If it’s disabled, then you will see an output like this;

getsebool: SELinux is disabled

We can turn it on using the following command:

sudo setsebool -P httpd_can_sendmail 1
sudo setsebool -P httpd_can_network_connect 1

If you are running your code on a shared hosting provider and trying to connect to some third-party SMTP provider like smtp.pepipost.com or smtp.sendgrid.com and getting some errors like this.

Possible Problem 5: PHPMailer SMTP Connection Failed Because Of SSL Support Issue With PHP

There are many popular cases for the failure of SMTP connection in PHPMailer and lack of SSL is one of that too.

There might be a case, that the Open SSL extension is not enabled in your php.ini which is creating the connection problem.

So, once you enable the extension=php_openssl.dll in the ini file.

Enable debug output, so that you can really see that SSL is the actual problem or not. PHPMailer gives a functionality by which you can get detailed logs of the SMTP connection.

You can enable this functionality by including the following code in your script;

$mail->SMTPDebug = 2;

By setting the value of SMTPDebug property to 2, you will be actually getting both server and client level transcripts.

For more details on the other parameter values, please refer the official PHPMailer Wiki.

In case you are using Godaddy hosting, then just enabling SSL might not fix your problem. Because there are other serious challenges with Godaddy which you can refer in the above godaddy section.

Possible Problem 6: PHPMailer Unable To Connect To SMTP Because Of The IPv6 Blocking Issue

There are some set of newer hosting companies which includes DigitalOcean provides IPv6 connectivity but explicitly blocks outgoing SMTP connections over IPv6 but allow the same over IPv4.

While this is not a major issue, because this can be workaround by setting the host property to an IPv4 address using the gethostbyname function.

$mail->Host = gethostbyname('smtp.pepipost.com');

Note: In this approach, you might face a certificate name check issue but that can be workaround by disabling the check, in SMTPOptions.
But, this is mostly an extreme case, most of the times it’s the port block issue by the provider, like DigitalOcean in this case.
So, it is important to first get confirmed whether the port is really unlocked or not, before digging further into the solution.

Possible Problem 7: Getting The Error «Could Not Instantiate Mail Function»

This issue happens primarily when your PHP installation is not configured correctly to call the mail() function. In this case, it is important to check the sendmail_path in your php.ini file. Ideally, your sendmail_path should point to the sendmail binary (usually the default path is /usr/sbin/sendmail).

Note: In case of Ubuntu/Debian OS, you might be having multiple .ini files (under the path /etc/php5/mods-available), so please ensure that you are making the changes at all the appropriate places.

If this configuration problem is not the case, then try further debugging and check whether you have a local mail server installed and configured properly or not. You can install any good mail server like Postfix.

Note: In case all of the above things are properly in place and you’re still getting this error of «Could not instantiate mail function», then try to see if you are getting more details of the error. If you see some message like «More than one from person» in the error message then it means that in php.ini the sendmail_path property already contains a from -f parameter and your code is also trying to add a second envelope from, which is actually not allowed.

What Is The Use Of IsSMTP()?

isSMTP() is been used when you want to tell PHPMailer class to use the custom SMTP configuration defined instead of the local mail server.

Here is a code snippet of how it looks like;

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 = "[email protected]"; // SMTP username
           $mail->Password = "mypasswword"; // SMTP password
           $Mail->Priority = 1;
           $mail->AddAddress("[email protected]","Name");
           $mail->SetFrom($visitor_email, $name);
           $mail->AddReplyTo($visitor_email,$name);
           $mail->Subject  = "This is a Test Message";
           $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.';
           }

Many times developers get the below error:

"SMTP -> ERROR: Failed to connect to server: Connection timed out (110). SMTP Connect() failed. Message was not sent. Mailer error: SMTP Connect() failed."

If you’re constantly getting the above error message, then just try identifying the problem as stated in the above sections.

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

ОШИБКА 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 failed to connect to server connection refused 111 smtp connect failed
  • Smtp error data not accepted что значит
  • Smtp error data not accepted smtp server error data end command failed detail
  • Smtp error could not connect to smtp host что это
  • Slui exe 0x2a 0x80041002 как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии