I’ve used PHPMailer on several projects but now I’m stuck. It gives me the error:
SMTP Error: Could not connect to SMTP host.
I’ve tried sending email from Thunderbird and it works ! But not through PHPMailer … Here are the settings from Thunderbird:
Server name: mail.exampleserver.com
Port: 587
Username: user@exampleserver.com
Secure Authentication: No
Connection Security: STARTTLS
I’ve compared these with the server at my last project where I used PHPMailer and they were:
Server name: mail.exampleserver2.com
Port: 465
Username: user@exampleserver2.com
Secure Authentication: No
Connection Security: SSL/TLS
My php code is:
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = SMTP_HOST; // SMTP servers
$mail->Port = SMTP_PORT; // SMTP servers
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = SMTP_USER; // SMTP username
$mail->Password = SMTP_PASSWORD; // SMTP password
$mail->From = MAIL_SYSTEM;
$mail->FromName = MAIL_SYSTEM_NAME;
$mail->AddAddress($aSecuredGetRequest['email']);
$mail->IsHTML(true); // send as HTML
Where I am wrong?
asked Aug 13, 2010 at 14:23
Ilian AndreevIlian Andreev
1,0513 gold badges12 silver badges18 bronze badges
1
Since this questions shows up high in google, I’d like to share here my solution for the case where PHP was just upgraded to version 5.6 (which has stricter SSL behavior).
The PHPMailer wiki has a section on this:
https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting#php-56-certificate-verification-failure
The suggested workaround is including the following piece of code:
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
This should work for PHPMailer 5.2.10 (and up).
Note: Obviously, and also as suggested in that wiki, this should be a temporary solution!
The correct fix for this is to replace the invalid, misconfigured or self-signed certificate with a good one.
answered Apr 4, 2016 at 14:32
Marten KoetsierMarten Koetsier
3,3492 gold badges24 silver badges36 bronze badges
9
Your problem is most likely this
Connection Security: STARTTLS
Connection Security: SSL/TLS
Those are 2 different protocols, are you using the correct one, whatever one you’re using in Thunderbird needs to be used.
Try setting the variable:
// if you're using SSL
$mail->SMTPSecure = 'ssl';
// OR use TLS
$mail->SMTPSecure = 'tls';
answered Aug 13, 2010 at 15:41
Viper_SbViper_Sb
1,80914 silver badges18 bronze badges
I had a similar issue and figured out that it was the openssl.cafile
configuration directive in php.ini
that needed to be set to allow verification of secure peers. You just set it to the location of a certificate authority file like the one you can get at http://curl.haxx.se/docs/caextract.html.
This directive is new as of PHP 5.6 so this caught me off guard when upgrading from PHP 5.5.
answered Jun 16, 2015 at 15:55
JasperJasper
75.6k14 gold badges150 silver badges146 bronze badges
2
I had the same problem and it was because PHPMailer realized the server supported STARTTLS so it tried to automatically upgrade the connection to an encrypted connection. My mail server is on the same subnet as the web server within my network which is all behind our domain firewalls so I’m not too worried about using encryption (plus the generated emails don’t contain sensitive data anyway).
So what I went ahead and did was change the SMTPAutoTLS to false in the class.phpmailer.php file.
/**
* Whether to enable TLS encryption automatically if a server supports it,
* even if `SMTPSecure` is not set to 'tls'.
* Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
* @var boolean
*/
public $SMTPAutoTLS = false;
answered Jan 31, 2017 at 21:26
SinaSina
3594 silver badges9 bronze badges
1
does mail.exampleserver.com exist ??? , if not try the following code (you must have gmail account)
$mail->SMTPSecure = "ssl";
$mail->Host='smtp.gmail.com';
$mail->Port='465';
$mail->Username = 'you@gmail.com'; // SMTP account username
$mail->Password = 'your gmail password';
$mail->SMTPKeepAlive = true;
$mail->Mailer = "smtp";
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->CharSet = 'utf-8';
$mail->SMTPDebug = 0;
admdrew
3,7824 gold badges26 silver badges39 bronze badges
answered Dec 27, 2010 at 16:19
Rami DabainRami Dabain
4,69912 gold badges62 silver badges104 bronze badges
Followed code worked for me:
$mail = new PHPMailer(true);
$mail->isSMTP();// Set mailer to use SMTP
$mail->CharSet = "utf-8";// set charset to utf8
$mail->SMTPAuth = true;// Enable SMTP authentication
$mail->SMTPSecure = 'tls';// Enable TLS encryption, `ssl` also accepted
$mail->Host = 'smtp.gmail.com';// Specify main and backup SMTP servers
$mail->Port = 587;// TCP port to connect to
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->isHTML(true);// Set email format to HTML
$mail->Username = 'Sender Email';// SMTP username
$mail->Password = 'Sender Email Password';// SMTP password
$mail->setFrom('example@mail.com', 'John Smith');//Your application NAME and EMAIL
$mail->Subject = 'Test';//Message subject
$mail->MsgHTML('HTML code');// Message body
$mail->addAddress('User Email', 'User Name');// Target email
$mail->send();
answered Jun 27, 2018 at 13:54
1
$mail->SMTPDebug = 2; // to see exactly what's the issue
In my case this helped:
$mail->SMTPSecure = false;
$mail->SMTPAutoTLS = false;
answered Jan 28, 2019 at 6:09
Well this is really old but I still want to share my solution.
If you are using phpmail with an local server like xampp turn off your antivirus.
That solved it for me
answered Jul 22, 2022 at 13:11
WaaalWaaal
576 bronze badges
Since this is a popular error, check out the PHPMailer Wiki on troubleshooting.
Also this worked for me
$mailer->Port = '587';
answered Apr 20, 2017 at 17:37
I recently dealt with this problem, and the cause of the problem turned out to be that the root certificate on the SMTP server that I was connecting to was the Sectigo root certificate that recently expired.
If you’re connecting to the SMTP server by SSL/TLS or STARTTLS, and you’ve not changed anything recently in the environment where your PHPMailer script is running, and this problem suddenly occurred — then you might want to check for an expired or invalid certificate somewhere in the certificate chain on the server.
You can view the server’s certificate chain using openssl s_client
.
For SSL/TLS on port 465:
openssl s_client -connect server.domain.tld:465 | openssl x509 -text
For STARTTLS on port 587:
openssl s_client -starttls smtp -crlf -connect server.domain.tld:587 | openssl x509 -text
answered Jun 10, 2020 at 18:45
mti2935mti2935
11.3k3 gold badges28 silver badges33 bronze badges
I had a similar issue. I had installed PHPMailer version 1.72 which is not prepared to manage SSL connections. Upgrading to last version solved the problem.
answered May 22, 2012 at 12:49
DavidDavid
2,94232 silver badges16 bronze badges
In my case in CPANEL i have ‘Register mail ids’ option where i add my email address and after 30 minutes it works fine with simple php mail function.
answered Feb 7, 2019 at 13:09
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.
Emails play a crucial role in online businesses. It can be bothersome when emails stop working. You may lose an urgent invite or important notification.
As part of our Support Services, we help website owners configure email services for their businesses and assist server owners to fix email errors.
One such commonly encountered error is “SMTP Error: Could not connect to SMTP host.” Today we’ll see what causes that error and how we fix it.
“Unable to connect to SMTP host.” – When do you see this error?
Majority of the SMB websites run on CMS such as WordPress, Joomla, WHMCS, etc. Most of these CMS software are configured to send emails from them.
These emails can be sent for various purposes – such as order confirmations, invoice delivery, contact form submissions, password resets, account registration and so on.
But due to any issues related to email server or configuration, this mail delivery can fail and give out the error “SMTP Error: Could not connect to SMTP host.”
The same error can present in different forms, such as:
SMTP -> ERROR: Failed to connect to server: (0)
SMTP Error: Could not connect to SMTP host. Message could not be sent.
Mailer Error: SMTP Error: Could not connect to SMTP host.
‘SMTP connect() failed’
What causes the email error “Unable to connect to SMTP host”
A number of reasons can lead to the SMTP connection error. That’s what often perplex the website owners when they see this error.
Here are the main causes we’ve identified in our debugging process.
1. Security restrictions
Exim servers, by default, have some security restrictions to avoid outbound spamming and to protect server IP reputation from blacklists. These restrictions lead to SMTP errors.
The setting in WHM ‘Server Configuration > Tweak Settings > Mail => ‘Restrict outgoing SMTP to root, exim, and mailman (FKA SMTP Tweak)’, blocks outgoing SMTP from website software.
Exim security restrictions
Another setting in WHM that provides the same restriction is, “WHM Home » Security Center » SMTP Restrictions”. This prevents users from bypassing the mail server to send mail.
WHM – SMTP restriction
To further secure mail servers, most servers have firewalls such as CSF, configured in them. Firewall rules can be configured to selectively or fully block connectivity to the SMTP ports.
Many ISPs also block the default SMTP port (25), to avoid spamming attempts. SELinux restriction is another security feature that can cause connection issues to mail server.
Website owners who use gmail as their SMTP server would face further security restrictions imposed by Google. By default, gmail does not allow connections from third party software.
If the option “access for less secure apps” is not enabled in the gmail account, users get the error “Unable to connect to SMTP host” in their websites.
2. Mail server configuration
The SMTP server is often specified as a hostname in the mail settings of the software. A DNS failure or temporary issues can affect the name resolution of the mail server.
In such scenarios, the mailing software will not be able to contact the SMTP server, causing connection errors. If the mail server has another service running on the SMTP port configured, the same issue occurs.
Another issue related to mail server is the lack of support for encryption. If the OpenSSL module is not configured properly or if the PHP extension is not working fine, it will throw errors during SMTP connections.
3. Client side mail settings
To send mails from website software, you need to configure the settings such as SMTP host, port and mail account username and password.
Any configuration mistakes in these settings can cause email errors due to authentication failures and show the message “Unable to connect to SMTP host”.
If the connection is attempted to a different mail server, it will not work. This can happen especially in the cases of website migration from one server to another.
Also, when encryption is not chosen for mail settings, many mail servers can reject the connection attempt and show “Unable to connect to SMTP host” error.
4. Software errors
Many website owners customize their software with plugins that enable them to send mails. Many others have custom code and tweaks done in their CMS.
Due to software updates, feature modifications, plugin issue or other code related bugs, the SMTP authentication support can stop working, giving out SMTP errors in the site.
How we fix the email error “Unable to connect to SMTP host”
To fix the error, we first figure out the cause for it. We examine the software settings, test the connectivity to mail server, and other security restrictions in the server to pinpoint the issue.
Once the cause for the error is identified, we make appropriate fixes such as re-configuring firewall rules and tweaking the security settings, so that mail delivery works fine.
For software updates and installs, we take proper backups and conduct mock installs beforehand, which help us to perform upgrades and fixes in websites without causing any errors.
Conclusion
Email errors are the most commonly encountered issues in servers. Today we saw why “Unable to connect to SMTP host” error happens in websites and how our Support Engineers 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.
SEE SERVER ADMIN PLANS
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
Have you encountered an error that says, “PHPMailer SMTP Error: Could not connect to SMTP host?”
Let’s solve it together.
PHPMailer is one of the most popular open source libraries for sending emails with PHP. While it’s easy to deploy and start sending emails, 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:
You may also like: A Complete Guide to Laravel 5.8 Installation.
Depending on your situation, there can be multiple reasons why this error occurs. So, please try to go through the different scenarios below and pick the one that is closest to your use case.
Possible Problem One: 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 behavior, which has caused this problem.
Here is a help doc on PHPMailer wiki that has a section on this issue.
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 Two: 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 there’s really nothing to debug. This occurs 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; many have expressed their frustration in form of issues on StackOverflow as well.
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 forge 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 landing in spam. In such a case, I would suggest going with a second option.
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 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 that 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 it can also create a really frustrating situation for developers like us.
The only solution to this is the same as I suggested above in the Godaddy section (Use Email APIs instead of any SMTP). Additionally, you could contact the hosting provider to allow connection to SMTP ports.
You might be asking, «How do I check whether your outgoing port (25, 587 or 465) is really blocked or not?»
- Trying doing telnet: Using telnet command you can actually test whether the port is opened or not. If Port 25 is not blocked, you will get a successful 220 response (text may vary). If Port 25 is blocked, you will get a connection error or no response at all.
//Type the following command to see if Port 25 is blocked on your network.
telnet pepipost.com 25
-
Trying 202.162.247.93... Connected to pepipost.com. Escape character is '^]'. 220 pepipost.com ESMTP Postfix
Trying 202.162.247.93... telnet: connect to address 202.162.247.93: Connection refused telnet: Unable to connect to remote host
- Use outPorts: outPorts is a very good open source project on GitHub that 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
.
- Use outPorts: outPorts is a very good open source project on GitHub that 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:
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, most it is most likely that SELinux is preventing PHP or the webserver from sending emails.
This problem occurs often 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.
SMTP connect() failed.
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 the lack of SSL is often a contributing factor.
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, you should 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.
Possible Problem 6: PHPMailer Unable to Connect to SMTP Because ff the IPv6 Blocking Issue
There are some set of newer hosting companies, including DigitalOcean, that provide IPv6 connectivity but explicitly block outgoing SMTP connections over IPv6 but allow the same over IPv4.
You can work around this issue 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.
This is mostly an extreme case. Most of the time, 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 used when you want to tell the 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 = "myemail@example.com"; // SMTP username
$mail->Password = "mypasswword"; // SMTP password
$Mail->Priority = 1;
$mail->AddAddress("myemail@gmail.com","Name");
$mail->SetFrom($visitor_email, $name);
$mail->AddReplyTo($visitor_email,$name);
$mail->Subject = "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 following 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.
If you like this tutorial, do like and share, and feel free to comment if you have any questions.
Related Articles
- Develop a REST API in PHP.
- How to Create a Simple and Efficient PHP Cache.
Opinions expressed by DZone contributors are their own.
Please check these things before submitting your issue:
- [ x ] Make sure you’re using the latest version of PHPMailer
- [ x ] Check that your problem is not dealt with in the troubleshooting guide, especially if you’re having problems connecting to Gmail or GoDaddy
- [ x ] Include sufficient code to reproduce your problem
- [ x ] If you’re having an SMTP issue, include the debug output generated with
SMTPDebug = 2
set - [ x ] If you have a question about how to use PHPMailer (rather than reporting a bug in it), tag a question on Stack Overflow with
phpmailer
, but search first!
Problem description
Hello,
Dude, I already tried everything you can imagine to solve this problem: «SMTP Error: Could not connect to SMTP host» when connecting to SMTP (Gmail).
Things I tried:
Turn off Kaspersky
Turn on Less Security Apps in Google account
Turn off firewall
set autotls = »;
Set autotls = false;
Uploaded my website in Hostinger and test from there and get the same error.
I know that is a common error with Gmail, but I think now there is something different from Troubleshooting.
Thanks
Code to reproduce
<?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
use PHPMailerPHPMailerSMTP;
session_start();
$nome = $_POST["nome"];
$email = $_POST["email"];
$mensagem = $_POST["mensagem"];
require_once("vendor/autoload.php");
$mail = new PHPMailer(true);
try {
//Server settings
$mail -> SMTPDebug = 3;
$mail -> isSMTP();
$mail -> Host = 'smtp.gmail.com';
$mail -> Port = 587;
$mail -> SMTPSecure = 'tls';
$mail -> SMTPAuth = true;
$mail -> Username = 'emailtesteprogramacao@gmail.com';
$mail -> Password = 'SECRET';
//Recipients
$mail -> setFrom('emailtesteprogramacao@gmail.com', 'Loja');
$mail -> addAddress('emailtesteprogramacao@gmail.com');
//Content
$mail -> isHTML(true);
$mail -> Subject = 'email de contato da loja';
$mail -> Body = '<html>de: {$nome}<br/>email: {$email}<br/>mensagem: {$mensagem}</html>';
$mail -> AltBody = 'de: {$nome}nemail:{$email}nmensagem: {$mensagem}';
$mail -> send();
$_SESSION["success"] = "Mensagem enviada com sucesso";
Header("Location: ../index.php");
die();
} catch (Exception $e) {
$_SESSION["danger"] = "Erro ao enviar mensagem " . $mail -> ErrorInfo;
Header("Location: ../index.php");
die();
}
Debug output
2017-12-09 12:58:40 Connection: opening to smtp.gmail.com:587, timeout=300, options=array()
2017-12-09 12:58:40 Connection: opened
2017-12-09 12:58:40 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP z17sm1312894qti.59 - gsmtp
2017-12-09 12:58:40 CLIENT -> SERVER: EHLO localhost
2017-12-09 12:58:41 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [2804:7f5:9384:5b66:f959:18c8:2de0:da8b]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2017-12-09 12:58:41 CLIENT -> SERVER: STARTTLS
2017-12-09 12:58:41 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
2017-12-09 12:58:41 Connection failed. Error #2: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed [C:xampphtdocscarreirainiciantebackendphpPHPMailervendorphpmailerphpmailersrcSMTP.php line 404]
SMTP Error: Could not connect to SMTP host.
2017-12-09 12:58:41 CLIENT -> SERVER: QUIT
2017-12-09 12:58:41
2017-12-09 12:58:41
2017-12-09 12:58:41 Connection: closed
SMTP Error: Could not connect to SMTP host.