hi, i’m new to php and i have been trying to send e-mail through php, phpmailer is the only class i find most recommended by most of the developers. i tried almost all solutions for my error. i cant find the fix. I have tried the link below, but didn’t get what to do, and googled for the solution, couldn’t find any, which works for me. tried almost all solutions, but it keeps showing me the same error.
Message could not be sent.Mailer Error:SMTP connect() failed.https://github.com/PHPMailer/PHPMailer/wiki/TroubleshootingAvailable
tried the above link, as im new to php, im stuck.
fr all smtpdebug: 1,2,3,4, its giving same error… but php mail() function is working fine.
and our hosting provider says this…
We have the following list of ports open on our shared hosting plans:
HTTP/HTTPS — 80/443
GMail — 465/587/995/993
TOMCAT — 8080
SMTP/IMAP/POP — 25/143/110
here is the code im using. please help me to resolve the error. thanx in advance.
<?php require 'phpmailer/PHPMailerAutoload.php'; $mail = new PHPMailer; //$mail->SMTPDebug = 3; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'userid@gmail.com'; // SMTP username $mail->Password = 'secret'; // SMTP password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to $mail->From = userid@gmail.com'; $mail->FromName = 'Mailer'; //$mail->addAddress('joe@example.net', 'Joe User'); // Add a recipient $mail->addAddress('name@mysite.com'); // Name is optional //$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments //$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body <b>in bold!</b>'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; if(!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'; } ?>
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.
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 :
- Modify the firewall rules on the server to allow outbound connections on ports like 465.
- Modify the SMTP restrictions on the server. Then, add particular website user to the list of users who can make outbound SMTP connections.
- Edit PHPMailer settings like Host, Port etc.
- 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»;
Отправляю сообщение, код ниже
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.profitway.net'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'info@profitway.net'; // SMTP username
$mail->Password = 'none'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom('info@profitway.net', 'Mailer');
$mail->addAddress('fast@yandex.ru', 'Joe User'); // Add a recipient
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo $e->getMessage();
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
Показывается следующая ошибка
2018-04-25 11:33:54 SMTP ERROR: Failed to connect to server: (0)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubl…
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubl… could not be sent. Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubl…
далее ставим
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
После добавление данного кода начинает все работать, но попадает в папку спам.
Я так понял, что проблема с сертификатами, но что за проблема именно и как ее исправить я не знаю. SSL сертификат стоит бесплатный, почту добавил через isp manager, доступ соотвественно оттуда взял, хост, порт и т.д. Почему не отправляет без данных настроек ?
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
Прошу помощи.
За последние 24 часа нас посетили 11419 программистов и 1119 роботов. Сейчас ищут 322 программиста …
-
- С нами с:
- 23 фев 2019
- Сообщения:
- 4
- Симпатии:
- 0
Всем привет.
Столкнулся с проблемой отправки на email из php. Сделал Web-страницу с формойа на которой пользователь вводит к примеру:
имя
email
сообщениеи нажимает кнопку Отправить. Данные передаются в php-файл. И они туда приходят. Проверял. А дальше нужно эти данные отправить на нужный мне адрес.
Скачал sendmail. Настроил параметры в php.ini
SMTP = smtp.gmail.com
smtp_port = 465
sendmail_from = user@gmail.com
где вместо user указал свой реальный логин
sendmail_path = «»C:webphpsendmailsendmail.exe» -t»больше в php.ini ничего не трогал на тему почты. Единственно что,
extension=openssl раскоментировал, когда не получалось отправить почту. Но это не помогло никак.в sendmail.ini
smtp_server=smtp.gmail.com
smtp_port=465
smtp_ssl=auto
error_logfile=error.log
debug_logfile=debug.log
auth_username=user@gmail.com
auth_password=!*******
from user@gmail.com
auth on
force_sender=shivara551@gmail.com
hostname=gmail.comвместо user и звездочек указал реальные свои данные
в итоге при отправке через функцию mail() ошибки не выдается и получаю в результате выполнения функции mail — true, однако в error.log sendmail-a и других log-файлах сообщается либо
Error connecting with SSL.
Пробовал через phpmailer, но тоже результата не добился.
Пробовал как с со своего домашнего компа с localhost-a, где настроен apache + php7, а так же с хостинга (что использую в статусе тестового периода).
В настройках отправки для sendmail.ini и php.ini пробовал указывать настройки серверов yandex.ru и gmail.com по отдельности.
Нашел информацию несколько лет назад на почтовых серверах стали использовать ssl и тот же mail() из php с ним не дружит. C Phpmailer успехов у меня так же нет. Там даже никаких Log-файлов нет. Не увидел во всяком случае. Как решить эту проблему?
Так же хотелось бы так же просветиться:
В былые времена, когда инет был медленным и для получения почты в основном использовались Outlook Express, The Bat и подобные..я помню указывал так же
smtp
pop3
порты
логин
пароль почтового аккаунта.Могу ли я с дома без доп. софта типа почтового сервера отправлять с localhost-a своего компа сообщение на нужный мне Email из php используя только Apache+ php+настройки сервера где у меня есть почта(например yandex.ru или gmail.com)?
-
- С нами с:
- 23 фев 2019
- Сообщения:
- 4
- Симпатии:
- 0
изменил в sendmail smtp_ssl с auto на tls
smtp_ssl=tls
получаю в итоге в log-файлах
Closed Gracefully
но письма не приходят все равно.
-
- С нами с:
- 23 фев 2019
- Сообщения:
- 4
- Симпатии:
- 0
Получилось через phpmailer с localhost отправлять почту. Но теперь другой вопрос. Когда я выкладываю папку на хостинг, там это не работает.
Выдает:Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Смотрел причину на https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
мол не включена openssl расширение
через phpinfo() посмотрел на хостинге настройки php.OpenSSL support enabled
OpenSSL Library Version OpenSSL 1.1.1a-freebsd 20 Nov 2018
OpenSSL Header Version OpenSSL 1.1.1a-freebsd 20 Nov 2018
Openssl default config /etc/ssl/openssl.cnf -
Команда форума
Модератор- С нами с:
- 20 июн 2012
- Сообщения:
- 8.493
- Симпатии:
- 1.732
Хостеры иногда закрывают выходы по SMTP на внешние сервера. Иногда разрешают это только по определённому порту. Так что напиши в поддержку, спроси, разрешено ли слать запросы на внешние SMTP и если да, то по какому порту
- Install PHPMailer
- Add PHPMailer To Application
PHPMailer is a highly popular, actively developed email-sending library for PHP. And it’s open-source.
For more information about PHPMailer, or to contribute, check out the PHPMailer GitHub page. Looking for a top-notch dedicated server host? You’ve come to the right place.
Below, we’ll give you a quick and easy example of a working script you can use in your local development environment or live on your InMotion Hosting server.
Install the PHPMailer Dependencies
You may be excited to get this code into your app, but first you need to make sure you’ve installed the necessary code library.
For this example, we’re going to be installing PHPMailer with Composer, since that is the preferred method for a great many PHP developers.
composer require phpmailer/phpmailer
That’s it! If you don’t have one already, composer will create your “vendor” directory and populate your autoload file.
Add The Code to Your App
Now is the fun part. But before running this code, make sure to change some of the example text we used below with your own information.
Sample | Replace with |
---|---|
[email protected] | Your sender email address |
mail.example.com | Your SMTP server name |
‘password’ | The sender email password |
[email protected] | The recipient email address |
Name of sender | Desired sender name |
Name of recipient | Desired recipient name |
Once you have switched out the example text, make sure to select the right development mode. This code can be used on your local server or a live production environment.
- For local development
- keep the
$developmentMode
variable set totrue
- For live server
- change the
$developmentMode
variable tofalse
We’re ready to begin.
<?php require "vendor/autoload.php"; $robo = '[email protected]'; use PHPMailerPHPMailerPHPMailer; use PHPMailerPHPMailerException; $developmentMode = true; $mailer = new PHPMailer($developmentMode); try { $mailer->SMTPDebug = 2; $mailer->isSMTP(); if ($developmentMode) { $mailer->SMTPOptions = [ 'ssl'=> [ 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ] ]; } $mailer->Host = 'mail.example.com'; $mailer->SMTPAuth = true; $mailer->Username = '[email protected]'; $mailer->Password = 'password'; $mailer->SMTPSecure = 'tls'; $mailer->Port = 587; $mailer->setFrom('[email protected]', 'Name of sender'); $mailer->addAddress('[email protected]', 'Name of recipient'); $mailer->isHTML(true); $mailer->Subject = 'PHPMailer Test'; $mailer->Body = 'This is a <b>SAMPLE<b> email sent through <b>PHPMailer<b>'; $mailer->send(); $mailer->ClearAllRecipients(); echo "MAIL HAS BEEN SENT SUCCESSFULLY"; } catch (Exception $e) { echo "EMAIL SENDING FAILED. INFO: " . $mailer->ErrorInfo; }
Source: MyPHPnotes
Well done! You’ve completed this tutorial. Now, if you have filled in all the correct data, you should be able to run this script in your browser and send mail to the recipient.
vlad_stuk 0 / 0 / 0 Регистрация: 18.12.2016 Сообщений: 14 |
||||
1 |
||||
17.07.2017, 16:59. Показов 10064. Ответов 12 Метки нет (Все метки)
Я пробовал различные почтовые сервисы но не могу решить проблему! Гуглил уже все что можно но проблема не решается(
__________________
0 |
97 / 47 / 17 Регистрация: 25.04.2017 Сообщений: 471 |
|
17.07.2017, 19:27 |
2 |
$mail = new PHPMailer; $mail = new PHPMailer();
1 |
Jodah 3802 / 3160 / 1326 Регистрация: 01.08.2012 Сообщений: 10,717 |
||||
17.07.2017, 19:33 |
3 |
|||
На экран выведутся логи. Изучай, ищи ошибки.
1 |
0 / 0 / 0 Регистрация: 18.12.2016 Сообщений: 14 |
|
17.07.2017, 19:51 [ТС] |
4 |
спасибо, что обратили внимание, но проблема не решается к сожалению( Добавлено через 2 минуты
0 |
3802 / 3160 / 1326 Регистрация: 01.08.2012 Сообщений: 10,717 |
|
17.07.2017, 20:10 |
5 |
vlad_stuk, т.е. send() возвращает true? Вы SMTPDebug установили до вызова send, верно?
1 |
vlad_stuk 0 / 0 / 0 Регистрация: 18.12.2016 Сообщений: 14 |
||||
17.07.2017, 20:21 [ТС] |
6 |
|||
да все верно но если я разкоментирую строку
; выводит ошибку: пароль от аккаунта введен правильно Добавлено через 10 минут
0 |
3802 / 3160 / 1326 Регистрация: 01.08.2012 Сообщений: 10,717 |
|
17.07.2017, 20:53 |
7 |
del
0 |
0 / 0 / 0 Регистрация: 18.12.2016 Сообщений: 14 |
|
17.07.2017, 20:55 [ТС] |
8 |
что значит DEL?
0 |
12384 / 7223 / 758 Регистрация: 09.09.2009 Сообщений: 28,185 |
|
17.07.2017, 21:01 |
9 |
эта строка ни о чем не говорит:
Error: Could not authenticate. 2017-07-17 17:08:27 CLIENT -> SERVER: QUIT 2017-07-17 17:08:27 SMTP connect() failed. ???
1 |
3802 / 3160 / 1326 Регистрация: 01.08.2012 Сообщений: 10,717 |
|
17.07.2017, 21:03 |
10 |
Сообщение было отмечено vlad_stuk как решение Решение
Гугл говорит, что вы не к mail.ru, а gmail.com пытаетесь прилогиниться (да и с чего бы mail.ru ссылался на документацию gmail?). И Gmail хочет, чтобы вы прошли типа авторизацию на новом устройстве. Попробуйте почитать тут. Либо попробуйте подключиться к другой почте, mail.ru, яндекс и т.п.
что значит DEL? Что-то написал -> понял, что написал фигню -> удалил.
0 |
0 / 0 / 0 Регистрация: 18.12.2016 Сообщений: 14 |
|
17.07.2017, 21:03 [ТС] |
11 |
да все это было мною просмотрено и также включено использование SMTP но ситуация не изменилась, даже когда у меня стоял MAMP *сервер сообщения почему то тоже не отправлялись. Сейчас у меня ХАМРР
0 |
3802 / 3160 / 1326 Регистрация: 01.08.2012 Сообщений: 10,717 |
|
17.07.2017, 21:05 |
12 |
но если я разкоментирую строку Она должна быть раскомментирована, не надо её скрывать.
0 |
0 / 0 / 0 Регистрация: 18.12.2016 Сообщений: 14 |
|
17.07.2017, 21:15 [ТС] |
13 |
Форумчане спасибо! Все заработало! Я Вам очень благодарен!
0 |
SMTP connect() failed is a common error in WordPress. If you get the error and hope to know how to solve it, then don’t hesitate to explore the blog today!
Why does the SMTP connect() failed error appear?
Normally, the error SMTP connect() failed turns out because the user misconfigured the SMTP mail sending method (Google Mail Service). Besides that, you know that PHPMailer is the default mailer in WordPress. In case there is something wrong that disallows the PHPMailer to contact the SMTP server, you can also get the error. Further, many other reasons and factors can also cause this error. In order to fix this issue, let’s take a look at the following methods.
How to fix the SMTP connect() failed error
If you desire to address the error SMTP connect() failed in an exact and effective way, it’s a good idea for you to identify the reason first, and then fix it. So, let’s check each possibility now!
SMTP host and port settings
- in the SMTP Host section, fill out your mail server’s name first and ensure that the DNS for the SMTP host is correct.
- The default SMTP port is 25. For mail servers, we will use custom ports 587 for SMTP in order to avoid spam.
- In some cases, the mail servers use firewall rules to restrict access to port 25. If you are in the case, it’s necessary for you to offer your IP white-listed to avoid the error.
- Now, let’s confirm that the connection of the SMTP server and port is good by using the command:
telnet domain.com 25
- After ensuring that the SMTP connection is ok, let’s use the suitable hostname and port number. If the connection is not ok, you will get the error SMTP connect() failed.
SMTP authentication details
As you know, each mail server has an authentication system with the purpose of validating the users before it allows them to connect to it and then send emails. Let’s make sure that the authentication details given are right, if not, WordPress can’t send emails and you may get the error SMTP connect() failed.
SMTP encryption settings
You should select SMTP with encryption if you need the email transmission secure. You can do that by choosing the option ‘Use SSL Encryption’ in the WordPress setting. However, in some email servers, you haven’t turned on SSL/TLS support yet. That means the mail can not get delivered and the error will happen.
Therefore, it’s a good suggestion for you to ensure that you configure the OpenSSL utility correctly in the mail server. Besides that, don’t forget to verify the SSL certificate with the command below:
openssl s_client -starttls smtp -crlf -connect mail.domain.com:25
If you are utilizing expired or self-signed certificates, this may cause the error SMTP connect() failed. Therefore, you can solve this issue by configuring SSL for the mail server or changing the SMTP from encryption to no encryption.
Support for 3rd party apps
Since Gmail servers have many security restrictions, they may block certain mail client apps. If you are in this case, it’s necessary for you to loosen the security. In order to do that, you need to access your Gmail, then open My Account -> Lestt Secure Apps -> Turn on Access for less secure apps.
WordPress SMTP plugins
Sometimes, the error SMTP connect() failed may appear because of the conflict with the SMTP plugin you are using. If this is the reason, you just need to stop using it and find alternative plugins. Here are some recommended WordPress SMTP Plugins for you to try.
Final Words
In conclusion, we are happy to offer you some solutions for the error SMTP connect() failed. If you think the blog is helpful, then don’t hesitate to share it with other users. Besides, don’t forget to leave your comment below if you have trouble related to this topic.
Furthermore, let’s have a look at our well-designed and easy-to-use free WordPress themes here. Thanks for your visit and have a great day!
- Author
- Recent Posts
Welcome to LT Digital Team, we’re small team with 5 digital content marketers. We make daily blogs for Joomla! and WordPress CMS, support customers and everyone who has issues with these CMSs and solve any issues with blog instruction posts, trusted by over 1.5 million readers worldwide.