Smtp error failed to connect to server network is unreachable 101 smtp connect failed

I need help please this is my code: require 'PHPMailerAutoload.php'; $mail = new PHPMailer; $mail->isSMTP(); $mail->Host = "smtp.gmail.com"; $mail->SMTPDebug = 2; $mail->SMTPAuth = tru...

I need help please
this is my code:

require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;

$mail->SMTPSecure = "tls";
$mail->Port = 587;

$mail->Username = 'some@gmail.com';
$mail->Password = 'somepass';
$mail->addAddress('another@gmail.com', 'Josh Adams');
$mail->Subject = 'PHPMailer GMail SMTP test';
$body = 'This is the HTML message body in bold!';
$mail->MsgHTML($body);
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

and I get this error:
2013-12-11 15:15:02 SMTP ERROR: Failed to connect to server: Network is unreachable (101) SMTP connect() failed. Mailer Error: SMTP connect() failed.

any help please?

asked Dec 11, 2013 at 15:35

kilinkis's user avatar

You might want to start by isolating this problem to determine whether it’s truly a network problem; or whether it’s specific to PHP mailer or your code. On your server, from a command prompt, try using telnet to connect to smtp.gmail.com on port 587, like so:

telnet smtp.gmail.com 587

You should see a response from smtp.gmail.com, like so:

Trying 173.194.74.108...
Connected to gmail-smtp-msa.l.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP f19sm71757226qaq.12 - gsmtp

Do you see this, or does the connection attempt hang and eventually time out? If the connection fails, it could mean that your hosting company is blocking outgoing SMTP connections on port 587.

answered Dec 12, 2013 at 14:04

mti2935's user avatar

mti2935mti2935

11.1k3 gold badges28 silver badges32 bronze badges

1

This worked for me:

change:

  $mail->SMTPSecure = 'ssl';
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = '465';

to

  $mail->SMTPSecure = 'tls';
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = '587';

answered Feb 15, 2020 at 12:54

yaya's user avatar

yayayaya

7,1471 gold badge35 silver badges35 bronze badges

The code below:

$mail->SMTPSecure = 'ssl';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Host = 'ssl://smtp.gmail.com:465';

Al Foиce    ѫ's user avatar

Al Foиce ѫ

4,12512 gold badges39 silver badges49 bronze badges

answered Sep 12, 2019 at 19:56

Baris Taskiran's user avatar

I was facing the same issues on Godaddy hosting so I spend lots of time and fix it by disabling the SMTP restriction on the server end.

SMTP code is for PHPMailer

 $mail = new PHPMailer(true);

try {
    //Server settings
    //$mail->SMTPDebug = SMTP::DEBUG_SERVER;                       //Enable verbose debug output
    $mail->SMTPDebug = 2;                       //Enable verbose debug output           
    //$mail->isSMTP();                                             //Send using SMTP

    $mail->Host         = "tls://smtp.gmail.com";
    $mail->SMTPAuth     = true;
    $mail->Username     = contact@example.in;
    $mail->Password     = SMTP_PASSWORD;
    $mail->SMTPSecure   = "tls";
    $mail->Port         = 587;
    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );
    //Recipients
    $mail->setFrom('contact@example.in', 'Online Order');
    $mail->addAddress('test@gmail.com');     //Add a recipient
    $mail->addReplyTo('contact@example.in', 'Jewellery');
   

    //Attachments
    //$mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name

    //Content
    $mail->isHTML(true);                                  //Set email format to HTML
    $mail->Subject = 'Order';
    $mail->Body    = 'This is test email content';
    $mail->AltBody = 'This is test email content';

    if($mail->send()){
        return '1';                 
    }else{
        return 'Order email sending failed';
    }

enter image description here

answered Feb 18, 2022 at 17:36

kantsverma's user avatar

kantsvermakantsverma

5771 gold badge11 silver badges27 bronze badges

change

$mail->SMTPSecure = "tls";

with

$mail->SMTPSecure = 'ssl';

Tom Tom's user avatar

Tom Tom

3,6835 gold badges34 silver badges40 bronze badges

answered Jul 1, 2014 at 16:03

Jesus's user avatar

1

I need help please
this is my code:

require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;

$mail->SMTPSecure = "tls";
$mail->Port = 587;

$mail->Username = 'some@gmail.com';
$mail->Password = 'somepass';
$mail->addAddress('another@gmail.com', 'Josh Adams');
$mail->Subject = 'PHPMailer GMail SMTP test';
$body = 'This is the HTML message body in bold!';
$mail->MsgHTML($body);
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

and I get this error:
2013-12-11 15:15:02 SMTP ERROR: Failed to connect to server: Network is unreachable (101) SMTP connect() failed. Mailer Error: SMTP connect() failed.

any help please?

asked Dec 11, 2013 at 15:35

kilinkis's user avatar

You might want to start by isolating this problem to determine whether it’s truly a network problem; or whether it’s specific to PHP mailer or your code. On your server, from a command prompt, try using telnet to connect to smtp.gmail.com on port 587, like so:

telnet smtp.gmail.com 587

You should see a response from smtp.gmail.com, like so:

Trying 173.194.74.108...
Connected to gmail-smtp-msa.l.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP f19sm71757226qaq.12 - gsmtp

Do you see this, or does the connection attempt hang and eventually time out? If the connection fails, it could mean that your hosting company is blocking outgoing SMTP connections on port 587.

answered Dec 12, 2013 at 14:04

mti2935's user avatar

mti2935mti2935

11.1k3 gold badges28 silver badges32 bronze badges

1

This worked for me:

change:

  $mail->SMTPSecure = 'ssl';
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = '465';

to

  $mail->SMTPSecure = 'tls';
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = '587';

answered Feb 15, 2020 at 12:54

yaya's user avatar

yayayaya

7,1471 gold badge35 silver badges35 bronze badges

The code below:

$mail->SMTPSecure = 'ssl';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Host = 'ssl://smtp.gmail.com:465';

Al Foиce    ѫ's user avatar

Al Foиce ѫ

4,12512 gold badges39 silver badges49 bronze badges

answered Sep 12, 2019 at 19:56

Baris Taskiran's user avatar

I was facing the same issues on Godaddy hosting so I spend lots of time and fix it by disabling the SMTP restriction on the server end.

SMTP code is for PHPMailer

 $mail = new PHPMailer(true);

try {
    //Server settings
    //$mail->SMTPDebug = SMTP::DEBUG_SERVER;                       //Enable verbose debug output
    $mail->SMTPDebug = 2;                       //Enable verbose debug output           
    //$mail->isSMTP();                                             //Send using SMTP

    $mail->Host         = "tls://smtp.gmail.com";
    $mail->SMTPAuth     = true;
    $mail->Username     = contact@example.in;
    $mail->Password     = SMTP_PASSWORD;
    $mail->SMTPSecure   = "tls";
    $mail->Port         = 587;
    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );
    //Recipients
    $mail->setFrom('contact@example.in', 'Online Order');
    $mail->addAddress('test@gmail.com');     //Add a recipient
    $mail->addReplyTo('contact@example.in', 'Jewellery');
   

    //Attachments
    //$mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name

    //Content
    $mail->isHTML(true);                                  //Set email format to HTML
    $mail->Subject = 'Order';
    $mail->Body    = 'This is test email content';
    $mail->AltBody = 'This is test email content';

    if($mail->send()){
        return '1';                 
    }else{
        return 'Order email sending failed';
    }

enter image description here

answered Feb 18, 2022 at 17:36

kantsverma's user avatar

kantsvermakantsverma

5771 gold badge11 silver badges27 bronze badges

change

$mail->SMTPSecure = "tls";

with

$mail->SMTPSecure = 'ssl';

Tom Tom's user avatar

Tom Tom

3,6835 gold badges34 silver badges40 bronze badges

answered Jul 1, 2014 at 16:03

Jesus's user avatar

1

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


Closed

kilinkis opened this issue

Dec 11, 2013

· 25 comments

Comments

@kilinkis

hello guys. I need help please
this is my code:

require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host       = "smtp.gmail.com";
$mail->SMTPDebug  = 2;
$mail->SMTPAuth   = true;           
$mail->SMTPSecure = "ssl";
$mail->Port       = 465;  
$mail->Username = 'some@gmail.com';
$mail->Password = 'somepass';
$mail->addAddress('another@gmail.com', 'Josh Adams');
$mail->Subject = 'PHPMailer GMail SMTP test';
$body    = 'This is the HTML message body <b>in bold!</b>';
$mail->MsgHTML($body);
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

and I get this error:
2013-12-11 15:15:02 SMTP ERROR: Failed to connect to server: Network is unreachable (101) SMTP connect() failed. Mailer Error: SMTP connect() failed.

any help please?

@Synchro

You shouldn’t use SSL on port 465; use TLS on 587. You might find it useful to refer to the example script that does exactly what you’re looking for — it’s why we wrote it.

Aside from that, if you’ve got connectivity problems, it’s nothing to do with PHPMailer.

@kilinkis

thanks Synchro :)
I tried TLS on 587 and got the same error.

Also, I tried that example before, in fact was the first thing I tried but it didnt work.

@Synchro

Well if your connection is failing it doesn’t matter if you try XYZ on 12345. Sort out your connectivity first.

@kilinkis

any help on how can I fixed that please? i see the php_info if you need to know something. Thanks

@myildi

First wait a day, because Gmail seems to have problems for the SMTP currently.

@Synchro

@kilinkis you’re looking in the wrong place — it’s like an accident has blocked the road ahead of you and traffic is at a standstill, and you’re asking us how to fix your car so you can drive on. Your car is not the problem!
As @myildi says, wait until it’s fixed, or use a different provider.

@Voyager2718

I’ve got the same problem.
My hosting provider is GoDaddy (which is a Linux Server), and I tried to use PHPMailer to send a mail via my Gmail acc, but it just show me «Connection refused (111) » every time. Could somebody help me???

@Synchro

It would possibly help if you actually read this thread before posting, and maybe even read the docs.

@Voyager2718

Uh, in fact, I trid TLS and 587 port. But doesn’t work either. Is this a bug or I should pay for this??

@Synchro

No, it’s not a bug. As this thread (and the docs) says, it’s a connectvity problem within your ISP. Ask them to fix it — it’s nothing to do with PHPMailer.

@Voyager2718

Oh..But I think there’re so many people faced this problem, why don’t they fix it?..

@Synchro

They do it deliberately — GoDaddy is something of a bottom-feeder amongst ISPs. They have a perpetual fight against people using their servers for spamming, so you have to ask them to allow outbound email. Alternatively, use an ISP that’s not cheap ‘n’ nasty.

@prasanna76

i am getting this error while using PHPMailer
SMTP connect() failed. Message could not be sent.Mailer Error: SMTP connect() failed.

@Synchro

So read this thread and try the suggestions in it instead of asking blindly.

@prasanna76

i tried all the ways but i not connecting

@prasanna76

this is wat am i trying

$mail = new PHPMailer;
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Mailer = 'smtp';
$mail->Host = 'smtp.gmail.com'; 
$mail->SMTPAuth = true;
$mail->Port= 587;
$mail->Username = 'prasanna.venkatesan83@gmail.com';
$mail->Password = '************';
$mail->SMTPSecure = 'tls';
$mail->From = 'prasanna.venkatesan83@gmail.com';
$mail->FromName = 'Prasanna';
$mail->addAddress($to, 'Prasanna');
$mail->addReplyTo($to, 'Prasanna');
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body    = $message;
//echo !extension_loaded('openssl')?"Not Available":"Available";
if(!$mail->send()) {
   echo 'Message could not be sent.';
   echo 'Mailer Error: ' . $mail->ErrorInfo;
   exit;
}

@Synchro

So you know for sure that your DNS is working perfectly and you can telnet to smtp.gmail.com outside of PHPMailer, as the docs suggest you try?

@prasanna76

how can i check DNS working or not?

@Synchro

As I said, read the docs that are linked from this thread!!! You claimed you already read them, but you clearly didn’t.

@prasanna76

@Synchro

Check your network configuration, ask your ISP. It’s not a PHPMailer problem.

@prasanna76

dig +short smtp.gmail.com

telnet smtp.gmail.com 587

i have tried this but it’s still not connected

@Synchro

Sigh. Right. Because it’s a network problem. Ask your ISP to fix it. There’s nothing we can do here.

@prasanna76

can i able to do it by myself can you tell the way to solve it

@Synchro

Yes, you can fix it yourself by asking your ISP. No, I can’t tell you how to do that.

@PHPMailer
PHPMailer

locked and limited conversation to collaborators

Nov 10, 2014

If you are setting up your WordPress site with a SMTP plugin or using the PHPMailer library for sending email from your web server, you might encounter this SMTP Error: Failed to connect to server: Connection refused (111)/Network is unreachable (101). It’s a common connectivity issue on most shared hosting servers. In this post I will explain the issue in detail and show you how you can resolve it to have a fully functional email/SMTP setup.

SMTP connection requires a port such 25/465/587. Based on the type of connection you may also need to use encryption (e.g. SSL/TLS) or no encryption at all. SSL encryption is mainly used on port 465 where as TLS on port 587. On some shared hosts port 465/587 are blocked by default. This makes it so PHPMailer/SMTP plugin can’t even connect to the remote SMTP server. Sometimes those ports are open but they don’t support encryption. This causes the email to be sent without any encryption which can be a security issue. Your remote SMTP host can also decide which connection to accept. For example: If you try to make a non-encrypted connection to a SMTP host like Gmail (smtp.gmail.com) it will refuse since the connection is not secure. In that case the error may look similar to this,

  • unable to connect to ssl://smtp.gmail.com:465 (connection refused)
  • unable to connect to smtp.gmail.com:587 (connection refused)

Connection refused (111)/Network is unreachable (101) error can also occur if your web host simply doesn’t allow external SMTP connection. This issue is common on a GoDaddy server where they only allow their own SMTP configuration. If you contact them regarding this issue they will assure you that port 465 and 587 are open (when they are not). If you get back to them again they will tell you to use their SMTP server host instead of your own. So if you are on a GoDaddy server and having this issue your SMTP configuration should look like the following:

  • SMTP Host/Server: relay-hosting.secureserver.net
  • Port: 25
  • SMTPAuth: false

This should allow you to send email from your web server without any interruption/error. If you come across a different solution for resolving this type of error feel free to share it in the comments.

Содержание

  1. SMTP ERROR: Failed to connect to server: Network is unreachable (101) #1077
  2. Comments
  3. How to Resolve SMTP Error: Failed to connect to server: Connection refused (111)/Network is unreachable (101)
  4. I can not send e-mail by SMTP
  5. Diego Marquez
  6. ruzbehraja
  7. 24x7server
  8. cPanelMichael
  9. Diego Marquez
  10. “Smtp error: Failed to connect to server” – Causes and Fixes
  11. What is “Smtp error: Failed to connect to server” ?
  12. What causes SMTP ERROR: Failed to connect to server ?
  13. 1. SMTP restrictions on the server.
  14. 2. Firewall restrictions on the server
  15. 3. Incorrect settings in PHPMailer
  16. 4. DNS failures
  17. How to fix SMTP Error: Failed to connect to server
  18. Conclusion
  19. PREVENT YOUR SERVER FROM CRASHING!
  20. 8 Comments
  21. PHPMailer не работает: есть ли новый способ сделать это?
  22. Решение

SMTP ERROR: Failed to connect to server: Network is unreachable (101) #1077

I have setup gmail SMTP for wordpress but while sending test mail it is showing the error

Connection: opening to ssl://smtp.gmail.com:80, timeout=300, options=array ( ‘ssl’ => array ( ‘verify_peer’ => false, ‘verify_peer_name’ => false, ‘allow_self_signed’ => true, ),)
Connection: Failed to connect to server. Error number 2. «Error notice: stream_socket_client(): unable to connect to ssl://smtp.gmail.com:80 (Network is unreachable)
SMTP ERROR: Failed to connect to server: Network is unreachable (101)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Server Info
OS: Linux server2.hostsoch.in 2.6.32-673.26.1.lve1.4.23.el6.x86_64 #1 SMP Thu Mar 9 15:13:22 EST 2017 x86_64
PHP version: 5.6.30
WordPress version: 4.8
WordPress multisite: No
openssl: Available
allow_url_fopen: Disabled
stream_socket_client: Available
fsockopen: Available
cURL: Available
cURL Version: 7.53.1, OpenSSL/1.0.1e

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

Why are you trying to send on port 80? That’s not going to work; use port 465 or use TLS on port 587.

I have tried it again with port 465 with SSL, still its giving the same error
Connection: opening to ssl://smtp.gmail.com:465, timeout=300, options=array ( ‘ssl’ => array ( ‘verify_peer’ => false, ‘verify_peer_name’ => false, ‘allow_self_signed’ => true, ),)
Connection: Failed to connect to server. Error number 2. «Error notice: stream_socket_client(): unable to connect to ssl://smtp.gmail.com:80 (Network is unreachable)
SMTP ERROR: Failed to connect to server: Network is unreachable (101)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Well, I can only conclude that the networking on your server is limited in some way — most likely that your ISP blocks outbound SMTP. Read the troubleshooting guide for some tests that will enable you to find out exactly what they are doing.

Also, you should never need to disable certificate verification when connecting to Google.

2018-06-15 12:02:39 Connection: opening to smtp.gmail.com:587, timeout=300, options=array ()
2018-06-15 12:07:00 Connection failed. Error #2: stream_socket_client(): unable to connect to smtp.gmail.com:587 (Network is unreachable) [/var/www/html/mail/class.smtp.php line 298]
2018-06-15 12:07:00 SMTP ERROR: Failed to connect to server: Network is unreachable (101)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

It really helps if you read the error message. This might come as a surprise, but when it says «Network is unreachable» it means it can’t reach your network. If you fix your network (probably removing whatever block your ISP puts on outbound SMTP), your script will be able to work; it’s not the script that’s causing the problem.

You could try the techniques listed in the troubleshooting guide, or ask your ISP.

Because you ignored the advice to use the latest version, you exposed your encoded password to everyone (I edited it out of your post), so I suggest you change it. This is just one reason you should not hijack other people’s threads.

Do you think that these links could have something to do with it?

It didn’t occur to you that those might tell you something? Or that looking in the guide to see if those are mentioned in there might be appropriate?

Источник

How to Resolve SMTP Error: Failed to connect to server: Connection refused (111)/Network is unreachable (101)

If you are setting up your WordPress site with a SMTP plugin or using the PHPMailer library for sending email from your web server, you might encounter this SMTP Error: Failed to connect to server: Connection refused (111)/Network is unreachable (101). It’s a common connectivity issue on most shared hosting servers. In this post I will explain the issue in detail and show you how you can resolve it to have a fully functional email/SMTP setup.

SMTP connection requires a port such 25/465/587. Based on the type of connection you may also need to use encryption (e.g. SSL/TLS) or no encryption at all. SSL encryption is mainly used on port 465 where as TLS on port 587. On some shared hosts port 465/587 are blocked by default. This makes it so PHPMailer/SMTP plugin can’t even connect to the remote SMTP server. Sometimes those ports are open but they don’t support encryption. This causes the email to be sent without any encryption which can be a security issue. Your remote SMTP host can also decide which connection to accept. For example: If you try to make a non-encrypted connection to a SMTP host like Gmail (smtp.gmail.com) it will refuse since the connection is not secure. In that case the error may look similar to this,

  • unable to connect to ssl://smtp.gmail.com:465 (connection refused)
  • unable to connect to smtp.gmail.com:587 (connection refused)

Connection refused (111)/Network is unreachable (101) error can also occur if your web host simply doesn’t allow external SMTP connection. This issue is common on a GoDaddy server where they only allow their own SMTP configuration. If you contact them regarding this issue they will assure you that port 465 and 587 are open (when they are not). If you get back to them again they will tell you to use their SMTP server host instead of your own. So if you are on a GoDaddy server and having this issue your SMTP configuration should look like the following:

  • SMTP Host/Server: relay-hosting.secureserver.net
  • Port: 25
  • SMTPAuth: false

This should allow you to send email from your web server without any interruption/error. If you come across a different solution for resolving this type of error feel free to share it in the comments.

Источник

I can not send e-mail by SMTP

Diego Marquez

Member

I am sending mail using phpmailer with google apps.

The error appears to me is:

SMTP ERROR: Failed to connect to server: Network is unreachable (101) 2016-08-30 23:09:33 SMTP connect() failed.

Code:
$mail->Host = «smtp.gmail.com»;
$mail->SMTPAuth = true;
$mail->SMTPSecure = ‘ssl’;
$mail->Port=465;

I made no change in the code and the server.

No have firewall.

ruzbehraja

Well-Known Member

Have you tried pinging smtp.gmail.com ?? Does it work?

Seems like a connectivity issue between your server / ISP and gmail.

Nothing to do with cPanel mostly.

24x7server

Well-Known Member

There is an issues with the firewall. Please try to disabled your server firewall and your script again.

cPanelMichael

Administrator

Your access level is listed as «Website Owner». Do you have root access to this system? If not, please report this issue to your web hosting provider, as it’s possible new firewall rules were added or changes to the «WHM >> SMTP Restrictions» option were made.

Diego Marquez

Member

Yes, I have root access.

«SMTP Restrictions» this disable.

You do not have the server firewall.

It seems that the port 465 and 587 blocked .

Источник

“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

Источник

PHPMailer не работает: есть ли новый способ сделать это?

Я следовал всем инструкциям в этом вопросе:

Но мне так и не удалось заставить работать PHPMailer. Я искал в другом месте — нет решений.

Вы можете просмотреть результаты здесь: https://unidrones.co.za/JuneSecond

Когда я пытаюсь отправить тестовое электронное письмо, используя учетные данные своей учетной записи gmail, он возвращает ошибку «SMTP connect () failed».

Я использую этот код шаблона:

Редактировать: я не знаю, есть ли новый способ отправлять электронные письма через PHP сейчас. Все учебные пособия и уроки, которые я использую, учат этому таким образом (то есть с использованием библиотеки PHPMailer).

Мне было нелегко найти библиотеку PHPMailer, включающую файл PHPMailerAutoload.php, из-за чего я думаю, что он немного устарел или устарел, но как еще я буду отправлять электронные письма? Я не знаю.

Решение

Причину, по которой вам трудно найти PHPMailerAutoload.php потому что он старый и больше не поддерживается. Получить последнюю и основывать свой код на Пример gmail предоставлен . Если вы новичок в PHP, научиться пользоваться композитором .

Эти три строки противоречат друг другу:

ssl:// в Host переопределяет tls в SMTPSecure , в результате чего он пытается использовать неявный TLS для порта, ожидающего явного TLS. Либо использовать ssl с портом 465 или tls с портом 587, а не другими комбо. В любом случае, похоже, это не твоя проблема.

Как руководство по устранению неполадок говорит об этой точной ошибке «SMTP connect () fail»:

Об этом часто говорят как о проблеме PHPMailer, но почти всегда это связано с локальным отказом DNS, блокировкой брандмауэра (например, как это делает GoDaddy) или другой проблемой в вашей локальной сети. Это означает, что PHPMailer не может связаться с SMTP-сервером, указанным в свойстве Host, но точно не говорит, почему.

Затем описывается несколько методов, которые вы можете использовать, чтобы попытаться точно определить, почему вы не можете подключиться. Удивительные вещи, документация.

Я попробовал вашу форму с некоторыми случайными данными и увидел, что вы не включили самое важное сообщение об ошибке в свой вопрос:

Это говорит о том, что ваш интернет-провайдер, вероятно, блокирует исходящий SMTP, поэтому у вас есть свой ответ — возможно, подтвердите, используя шаги, предложенные в руководстве ( telnet и т. д.) и обратитесь к документации или поддержке вашего интернет-провайдера.

У вас также есть серьезное упущение — вы не устанавливаете адрес «от»:

Обратите внимание, что если вы отправляете через gmail, вы можете использовать только адрес своей учетной записи или заданные псевдонимы (заданные в настройках gmail), а не произвольные адреса.

Между тем, это довольно сумасшедшая вещь для реализации, так как у вас все равно есть — зачем кому-то вводить свои учетные данные Gmail в такой форме?

Источник

443 votes

4 answers

Get the solution ↓↓↓

I need help please
this is my code:

require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;

$mail->SMTPSecure = "tls";
$mail->Port = 587;

$mail->Username = '[email protected]';
$mail->Password = 'somepass';
$mail->addAddress('[email protected]', 'Josh Adams');
$mail->Subject = 'PHPMailer GMail SMTP test';
$body = 'This is the HTML message body in bold!';
$mail->MsgHTML($body);
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

and I get this error:
2013-12-11 15:15:02 SMTP ERROR: Failed to connect to server: Network is unreachable (101) SMTP connect() failed. Mailer Error: SMTP connect() failed.

any help please?

2021-10-24

Write your answer


430

votes

Answer

Solution:

You might want to start by isolating this problem to determine whether it’s truly a network problem; or whether it’s specific to PHP mailer or your code. On your server, from a command prompt, try using telnet to connect to smtp.gmail.com on port 587, like so:

telnet smtp.gmail.com 587

You should see a response from smtp.gmail.com, like so:

Trying 173.194.74.108...
Connected to gmail-smtp-msa.l.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP f19sm71757226qaq.12 - gsmtp

Do you see this, or does the connection attempt hang and eventually time out? If the connection fails, it could mean that your hosting company is blocking outgoing SMTP connections on port 587.


443

votes

Answer

Solution:

This worked for me:

change:

  $mail->SMTPSecure = 'ssl';
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = '465';

to

  $mail->SMTPSecure = 'tls';
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = '587';


641

votes

Answer

Solution:

The code below:

$mail->SMTPSecure = 'ssl';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Host = 'ssl://smtp.gmail.com:465';


367

votes

Answer

Solution:

change

$mail->SMTPSecure = "tls";

with

$mail->SMTPSecure = 'ssl';


Share solution ↓

Additional Information:

Date the issue was resolved:

2021-10-24

Link To Source

Link To Answer
People are also looking for solutions of the problem: unable to determine current zabbix database version: the table «dbversion» was not found.

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

Diego Marquez


  • #1

I am sending mail using phpmailer with google apps.

The error appears to me is:

SMTP ERROR: Failed to connect to server: Network is unreachable (101) 2016-08-30 23:09:33 SMTP connect() failed.

Code:
$mail->Host = «smtp.gmail.com»;
$mail->SMTPAuth = true;
$mail->SMTPSecure = ‘ssl’;
$mail->Port=465;

I made no change in the code and the server.

No have firewall.

  • #2

Have you tried pinging smtp.gmail.com ?? Does it work?

Seems like a connectivity issue between your server / ISP and gmail.

Nothing to do with cPanel mostly.

  • #3

Hello :),

There is an issues with the firewall. Please try to disabled your server firewall and your script again.

cPanelMichael


  • #4

Hello,

Your access level is listed as «Website Owner». Do you have root access to this system? If not, please report this issue to your web hosting provider, as it’s possible new firewall rules were added or changes to the «WHM >> SMTP Restrictions» option were made.

Thank you.

Diego Marquez


  • #5

Yes, I have root access.

«SMTP Restrictions» this disable.

You do not have the server firewall.

It seems that the port 465 and 587 blocked …

Any other suggestions?

thanks

  • #6

You have to determine whether it’s a network problem; or issues with PHP mailer or your code.
On your server, from a command prompt, try using telnet to connect to smtp.gmail.com on port 587 and 465, like so:

telnet smtp.gmail.com 587

You should see a response from smtp.gmail.com as Connected.
If the connection attempt hang and eventually time out it could mean that your hosting company is blocking outgoing SMTP connections on port 587 and 465

Diego Marquez


  • #7

The problem was solved.

The server network was in trouble.

cPanelMichael


  • #8

I’m happy to see the issue is now resolved. Thank you for updating us with the outcome.

  • #9

In some cases a simple request to your ISP will get them to unblock Port 25 for you, or sometimes simply using Port 587 for your SMTP will work, but in some cases your ISP may instead require you to use their SMTP server setting for outgoing mail.

  • #1

Hi guys,
I use the latest version directly and send mail via gmail.
I installed plesk to try on the same server and mail went fine.
I installed Directadmin and try again, mail is not going.
Error: SMTP -> ERROR: Could not connect to server: Network cannot be accessed (101)

PHP:

require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->IsHTML(true);
$mail->SetLanguage("tr", "phpmailer/language");
$mail->CharSet  ="utf-8";
$mail->Username = "[email protected]";
$mail->Password = "password";
$mail->SetFrom("[email protected]", "Name Surname");
$mail->AddAddress("[email protected]");
$mail->Subject = "M Title";
$mail->Body = "Message";
if(!$mail->Send()){
    echo "Error : ".$mail->ErrorInfo;
} else {
    echo "Okk";
}

smtalk


  • #2

Please check SMTP_BLOCK setting in CSF firewall.

  • #4

Please check SMTP_BLOCK setting in CSF firewall.

SMTP_BLOCK = OFF

But it still doesn’t work, please help. I’m just learning.

smtalk


  • #5

SMTP_BLOCK = OFF

But it still doesn’t work, please help. I’m just learning.

Did you restart CSF after? And I think it should be numerical (0).

  • #6

Did you restart CSF after? And I think it should be numerical (0).

Yes, I even restarted the server.

The result is still the same, I don’t know what to do.

smtalk


  • #7

Maybe outbound port 465 is blocked then? Try disabling CSF firewall to make sure it’s not related.

  • #8

Maybe outbound port 465 is blocked then? Try disabling CSF firewall to make sure it’s not related.

I tried this, making it completely passive but still getting the same error.

smtalk


  • #9

I tried this, making it completely passive but still getting the same error.

Try this from the server:

Code:

telnet smtp.gmail.com 465

If it does not work — please try contacting your datacenter, as it’s likely an external firewall.

  • #10

Try this from the server:

Code:

telnet smtp.gmail.com 465

If it does not work — please try contacting your datacenter, as it’s likely an external firewall.

Code:

[[email protected] ~]# telnet smtp.gmail.com 465
Trying 64.233.184.109...
Connected to smtp.gmail.com.
Escape character is '^]'.
Connection closed by foreign host.

smtalk


  • #11

Code:

[[email protected] ~]# telnet smtp.gmail.com 465
Trying 64.233.184.109...
Connected to smtp.gmail.com.
Escape character is '^]'.
Connection closed by foreign host.

It works from the server. So, it must be CSF not disabled (and still disallowing it from your end-customer (you can SSH as him to check)), or some misconfiguration on PHP side.

  • #12

I don’t know for sure, it says port 25 for scripts but maybe it also works for port 465 and since you’re using a script try this:
SMTP_ALLOWLOCAL = «1»
in CSF.

Or disable csf totally so everything is open and see if it works then. If yes, you can be sure it’s a csf setting, if not, must be a misconfiguration.

  • #13

Firewall is completely closed but it still doesn’t work. I reinstalled a few times but the result is the same.

I’m setting up Plesk working there. I couldn’t find any results.

  • #15

Connection refused (111)/Network is unreachable (101) error can also occur if your web host simply doesn’t allow external SMTP connection. … So if you are on a GoDaddy server and having this issue your SMTP configuration should look like the following: SMTP Host/Server: relay-hosting.secureserver.net. Port: 25. forpc jfi.cam/jiofilocalhtml/

  • #16

if your web host simply doesn’t allow external SMTP connection.

In that case it wouldn’t work on Plesk either. But he said it’s working with Plesk so it must be another issue.

However, you and @shiroamada are both answering to a topic of over a year old. It will be fixed in the mean time, so please don’t reply solutions to such old posts.
Also, it’s not really a good idea to put a username in the «smtp_allowuser» unless maybe you only have one user. If you need that, you have set something else not correct.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Smtp error failed to connect to server connection timed out 110 phpmailer
  • 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 что это

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

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