Содержание
- [Tutorial] PHPMailer SMTP Error: Could not connect to SMTP host.
- Solve this common SMTP error with PHPMailer.
- SMTP Error: Could Not Connect to SMTP Host
- Possible Problem One: Problem With The Latest Version Of PHP
- Possible Problem Two: Using Godaddy as the Hosting Provider
- 1. Use Godaddy SMTP Instead of any Third Party:
- 2. Use Email APIs Instead Of Any SMTP:
- Possible Problem 3: Getting SMTP Connection Failure on a Shared Hosting Provider
- Possible Problem 4: SELinux Blocking Issue
- Possible Problem 5: PHPMailer SMTP Connection Failed Because of SSL Support Issue With PHP
- Possible Problem 6: PHPMailer Unable to Connect to SMTP Because ff the IPv6 Blocking Issue
- Possible Problem 7: Getting the Error “Could Not Instantiate Mail Function”
- What Is the Use of IsSMTP()?
- ОШИБКА SMTP: не удалось подключиться к серверу: отказано в разрешении (13)
- Решение
- Другие решения
- Installing and upgrading help
- SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- Installing and upgrading help
- SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
- ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
[Tutorial] PHPMailer SMTP Error: Could not connect to SMTP host.
Solve this common SMTP error with PHPMailer.
Join the DZone community and get the full member experience.
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:
SMTP Error: Could Not Connect to SMTP Host
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:
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:
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;
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:
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.
-
- 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 .
Possible Problem 4: SELinux Blocking Issue
In case you are some error like the following:
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.
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:
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 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:
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.
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;
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.
Источник
ОШИБКА SMTP: не удалось подключиться к серверу: отказано в разрешении (13)
Я пытаюсь заставить мой phpmailer работать на моем хостинге (freehostia.com) и я всегда получаю эту ошибку. Имя пользователя и пароль в моем gmail верны, а остальные настройки примерно такие:
OpenSSL не комментируется в php.ini также. Я что-то здесь упускаю? Спасибо.
Полное сообщение об ошибке:
Решение
Давайте сначала ответим на ответ! Попробуйте с помощью следующей команды:
если это показывает: httpd_can_sendmail —> off
включите это с этим:
затем попробуйте отправить письмо еще раз.
Это решение исходит из этого великого страница .
Как было указано в этой статье, вам также может понадобиться sudo setsebool -P httpd_can_network_connect 1 , Хотя для моего CentOS 7 vm, размещенного на DigitalOcean, это не обязательно.
Проблема, с которой я столкнулся, заключалась в том, что я не мог отправлять электронные письма с веб-сайта Drupal с модулем поддержки аутентификации SMTP, который опирается на PHPMailer. И используемый SMTP-сервер был Google.
Кстати, я подозревал, что это была проблема с сертификатом OpenSSL и провел некоторый тест, но не повезло. Итак, установив $SMTPDebug Уровень 2 из исходного кода PHPMailer, я смог перехватить сообщение об ошибке «Отказано в доступе (13)».
Другие решения
Это говорит о том, что обертки fopen или функции сокетов отключены в вашей установке PHP. Не редкость в виртуальном хостинге. Бег phpinfo() должен сказать вам.
Вы можете, вероятно, использовать $mail->isMail(); и пропустите аутентификацию для отправки через почтовый сервер ISP вместо SMTP, но остерегайтесь проблем SPF.
проблема в том, что бесплатный хостинг freehostia блокирует исходящие письма.
Freehostia блокирует список ниже в свободном плане. (Шоколад)
если это не работает, попробуйте ниже для php-кода.
Источник
Installing and upgrading help
SMTP -> ERROR: Failed to connect to server: Permission denied (13)
ERROR: Failed to connect to server: Permission denied (13)» >SMTP -> ERROR: Failed to connect to server: Permission denied (13)
Please, somebody help me!
SMTP working, ports not blocking
When I try to send a letter, get error:
ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
What have you specified as the SMTP host in Moodle under Site administration/Server/Email?
ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
I specified «news.mydomain.com». SMTP login, SMTP password no need.
I have no problem with sending messages from the server .
Thanks for your help!
ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
Are you using a valid e-mail server name. The «news» part of «news.mydomain.com» implies that you’re using a usenet server, not an e-mail server. If so, does that usenet server allow e-mail relaying?
I’d be very weary of setting up an e-mail server that isn’t password protected! That’s a spammers paradise. Are you sure that a password isn’t required?
ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
The problem was in selinux : «httpd_can_sendmail —> on».
Thanks for your help.
ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
Ran Into this issue today — Thanks so much for this post — Saved me even more time spent
ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
I’m having the same problem. What file did you change this setting in?
Источник
Installing and upgrading help
SMTP -> ERROR: Failed to connect to server: Permission denied (13)
ERROR: Failed to connect to server: Permission denied (13)» >SMTP -> ERROR: Failed to connect to server: Permission denied (13)
Please, somebody help me!
SMTP working, ports not blocking
When I try to send a letter, get error:
ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
What have you specified as the SMTP host in Moodle under Site administration/Server/Email?
ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
I specified «news.mydomain.com». SMTP login, SMTP password no need.
I have no problem with sending messages from the server .
Thanks for your help!
ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
Are you using a valid e-mail server name. The «news» part of «news.mydomain.com» implies that you’re using a usenet server, not an e-mail server. If so, does that usenet server allow e-mail relaying?
I’d be very weary of setting up an e-mail server that isn’t password protected! That’s a spammers paradise. Are you sure that a password isn’t required?
ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
The problem was in selinux : «httpd_can_sendmail —> on».
Thanks for your help.
ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
Ran Into this issue today — Thanks so much for this post — Saved me even more time spent
ERROR: Failed to connect to server: Permission denied (13)» >Re: SMTP -> ERROR: Failed to connect to server: Permission denied (13)
I’m having the same problem. What file did you change this setting in?
Источник
Synchro,
Tried the reply submitted by you, first let me commit that I am just an enthusiast user, and so am not so I might miss a point or two due to lack of knowledge, so please pardon if you feels so,
Next, «fopen» is allowed from my php.ini file, because I have used this function more then once, but for fcgi socket, I really don’t know that.
I have tried the above suggestion by keeping $mail->SMTPDebug = 4; and using tls on 587, and here is the error, I am getting
2014-08-31 18:28:49 Connection: opening to smtp.gmail.com:587, t=10, opt=array ( )
2014-08-31 18:28:59 SMTP ERROR: Failed to connect to server: Permission denied (13)
2014-08-31 18:28:59 SMTP connect() failed. array(1) { [0]=> string(46) "SMTP connect() failed.
Is their a chance that and I am (my gmail account) not allowed to use smtp.gmail.com.
Also, for you reference I am putting my code below (removing password, and only the part which is responsible for sending mail, not the whole)
if (empty($errors)) {
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try {
$mail->SMTPDebug = 4; // 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 = 'nileshcool@gmail.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect, tls=587, ssl=465
$mail->From = 'admin@teknaps.com';
$mail->FromName = 'Teknaps Contact Form';
$mail->addAddress($fields['email'], $fields['name']); // Add a recipient
$mail->addReplyTo($fields['email'], $fields['name']);
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->isHTML(false); // Set email format to HTML
$mail->Subject = $fields['subject'];
$mail->Body = $fields['message'];
$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';
}
$errors[] = "Send mail sucsessfully";
} catch (phpmailerException $e) {
$errors[] = $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
$errors[] = $e->getMessage(); //Boring error messages from anything else!
}
}
- Главная
- Блог
- Поиск
- Контакты
Подробный поиск
|
Android |
Apache |
Bitrix CMS |
Centos |
|
Class |
CSS |
Debian |
Delphi |
|
Docker |
Drupal |
git |
HTML |
|
JavaScript |
Joomla |
JQuery |
JQuery UI |
|
Laravel |
Linux |
MODx |
MTG |
|
openCart |
PHP |
Python |
raspberry pi 3 / arduino |
|
regexp |
Script / Tool |
Smarty |
Soft |
|
SQL |
WebAsyst (shop-script) |
WordPress |
Алгоритмы |
|
Безопасность |
Игры |
Книги |
Настройка / Конфиги |
|
Сторонние сервисы |
Управление проектами |
Фильмы |
18.11.2021
При отправке писем через PHPMailer, вылетает ошибка:
PHPMailer: SMTP ERROR: Failed to connect to server: Permission denied (13)
Решение довольно простое и оно описано в официальной документации.
Заходим на сервер по SSH и выполняем:
sudo setsebool -P httpd_can_sendmail 1 sudo setsebool -P httpd_can_network_connect 1
Как я понимаю, если selinux выключен, то такой ошибки не возникает.
Категории: PHP, Настройка / Конфиги, Сторонние сервисы, Linux
Hi All!
Please, somebody help me!
Version Moodle 1.9.11+ (Build: 20110413)
SMTP working, ports not blocking
When I try to send a letter,get error:
SMTP -> ERROR: Failed to connect to server: Permission denied (13) ERROR: SMTP Error: Could not connect to SMTP host.
SMTP -> ERROR: Failed to connect to server: Permission denied (13) ERROR: SMTP Error: Could not connect to SMTP host.
Where to look for an error. In the Apache logs there is nothing in the logs of postfix too.
What have you specified as the SMTP host in Moodle under Site administration/Server/Email?
I specified «news.mydomain.com». SMTP login, SMTP password no need.
I have no problem with sending messages from the server.
Thanks for your help!
Are you using a valid e-mail server name. The «news» part of «news.mydomain.com» implies that you’re using a usenet server, not an e-mail server. If so, does that usenet server allow e-mail relaying?
I’d be very weary of setting up an e-mail server that isn’t password protected! That’s a spammers paradise… Are you sure that a password isn’t required?
Problem solved!!!
The problem was in selinux : «httpd_can_sendmail —> on».
Thanks for your help.
Average of ratings: Useful (1)
Ran Into this issue today — Thanks so much for this post — Saved me even more time spent
I’m having the same problem. What file did you change this setting in?
Добрый день!
Я пытаюсь заставить мой phpmailer работать на моем хостинге (freehostia.com) и я всегда получаю эту ошибку. Имя пользователя и пароль в моем gmail верны, а остальные настройки примерно такие:
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'tls://smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mymail@gmail.com'; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('mymail@gmail.com', 'ASAPHOT Administrator'); // Add a recipient
$mail->addAddress('sorianorobertc@gmail.com'); // Name is optional
$mail->addReplyTo('mymail@gmail.com', 'ASAPHOT Administrator');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'it works';
$mail->Body = 'it works';
$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';
}
OpenSSL не комментируется в php.ini также. Я что-то здесь упускаю? Спасибо.
Полное сообщение об ошибке:
Connection: opening to smtp.gmail.com:587, timeout=300, options=array ()
SMTP ERROR: Failed to connect to server: Permission denied (13)
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
3
Решение
Давайте сначала ответим на ответ! Попробуйте с помощью следующей команды:
$ getsebool httpd_can_sendmail
если это показывает: httpd_can_sendmail --> off
включите это с этим:
$ sudo setsebool -P httpd_can_sendmail 1
затем попробуйте отправить письмо еще раз.
Это решение исходит из этого великого страница.
Как было указано в этой статье, вам также может понадобиться sudo setsebool -P httpd_can_network_connect 1, Хотя для моего CentOS 7 vm, размещенного на DigitalOcean, это не обязательно.
Проблема, с которой я столкнулся, заключалась в том, что я не мог отправлять электронные письма с веб-сайта Drupal с модулем поддержки аутентификации SMTP, который опирается на PHPMailer. И используемый SMTP-сервер был Google.
Кстати, я подозревал, что это была проблема с сертификатом OpenSSL и провел некоторый тест, но не повезло. Итак, установив $SMTPDebug Уровень 2 из исходного кода PHPMailer, я смог перехватить сообщение об ошибке «Отказано в доступе (13)».
3
Другие решения
Это говорит о том, что обертки fopen или функции сокетов отключены в вашей установке PHP. Не редкость в виртуальном хостинге. Бег phpinfo() должен сказать вам.
Вы можете, вероятно, использовать $mail->isMail(); и пропустите аутентификацию для отправки через почтовый сервер ISP вместо SMTP, но остерегайтесь проблем SPF.
1
проблема в том, что бесплатный хостинг freehostia блокирует исходящие письма.
0
Freehostia блокирует список ниже в свободном плане. (Шоколад)
-рассылка
-локон
-мыло получить
-XML получить
0
use this
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "ssl://smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port
если это не работает, попробуйте ниже для php-кода.
почта ($ к, $ вопросу, $ сообщение);
-2
Добрый день!
Я пытаюсь заставить мой phpmailer работать на моем общем хостинге (freehostia.com), и я всегда получаю эту ошибку. Имя пользователя и пароль моего gmail верны, а остальные параметры:
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'tls://smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('[email protected]', 'ASAPHOT Administrator'); // Add a recipient
$mail->addAddress('[email protected]'); // Name is optional
$mail->addReplyTo('[email protected]', 'ASAPHOT Administrator');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'it works';
$mail->Body = 'it works';
$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';
}
openssl также раскомментирован в php.ini. Я что-то упустил? Спасибо.
Завершить сообщение об ошибке:
Connection: opening to smtp.gmail.com:587, timeout=300, options=array ()
SMTP ERROR: Failed to connect to server: Permission denied (13)
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
27 нояб. 2015, в 07:13
Поделиться
Источник
3 ответа
Это говорит о том, что в вашей установке PHP отключены обертки fopen или функции сокетов. Не редкость в общем хостинге. Выполнение phpinfo() должно сказать вам.
Возможно, вы можете использовать $mail->isMail(); и пропустить авторизацию для отправки через почтовый сервер ISP вместо SMTP, но остерегайтесь проблем с SPF.
Synchro
27 нояб. 2015, в 09:19
Поделиться
проблема заключается в том, что бесплатный хостинг freehostia блокирует исходящие письма.
FewFlyBy
02 дек. 2015, в 09:41
Поделиться
use this
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "ssl://smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port
если это не работает, чем попробуйте ниже для php-кода.
почта ($ к, $при условии, $сообщение);
kaushik
27 нояб. 2015, в 06:12
Поделиться
Ещё вопросы
- 0curl_file_create из файлового ресурса, используя mongo gridfs
- 0Включение еще одного объединения в таблицу MYSQL
- 0Невозможно отправить электронное письмо с использованием codeigniter
- 1Как обновить сущность в jpa?
- 0синтаксическая ошибка, неожиданный T_PRIVATE — Magento
- 1Проблема записи на приложение для Android
- 1Значение шифрования Java не соответствует значению шифрования javascript
- 0Включение содержимого страницы PHP в другой
- 1группировка данных zingchart и выборка вниз
- 0записать данные в нужную строку в уже существующий файл
- 1Почему эта сортировка вставки не может сортировать массивы объектов? (но могут другие значения)
- 0JQuery Автозаполнение проблемы
- 1код сценария Java для предотвращения закрытия браузера пользователем без предупреждения в Chrome
- 1Переход в Навбар при прокрутке вниз
- 1Pandas — Python отбрасывает строки, если столбец содержит несколько критериев
- 0Сообщение об ошибке загрузки файла Blueimp для недопустимых файлов
- 0ASP.NET MVC4 руководство ajax пост без проверки
- 0База данных mysql drop, которая существует с тем же именем
- 1Настройка цвета фона элемента списка теряет подсветку
- 0Preg заменить все IMG, когда SRC не на пример домена
- 0Как установить высоту тела равную длине массива в угловых
- 0MySQL запрос возвращает только один пост
- 0Массив фильтров во втором контроллере
- 0Переадресация нагрузки nginx 404
- 1Создание пользовательской аннотации с использованием Spring, который поддерживает гибкую подпись метода
- 1Как получилось, что в Localytics было зарегистрировано 2 сессии за запуск приложения?
- 1NullPointerException при попытке добавить слой Orm с помощью Hibernate
- 0Как сделать директиву в контроллере?
- 0Магистраль: потерянная ссылка на фактический вид?
- 0как получить скрытое значение с той же страницы
- 1использование openpyxl Tokenizer для разбора операторов Excel IF
- 0Ограничение загрузки изображений в jpg в ASP .NET MVC
- 0Импортируйте CSV в базу данных, используя CakePHP
- 0HTML-форма без входного селектора в коде
- 0Простой поиск в массиве C ++
- 1Как перевести ячейку в режим редактирования, как только она получит фокус
- 0Изучаю AngularJS и нужно составить сгруппированный список
- 0Значение не в состоянии перейти с одной страницы на другую
- 1Как смоделировать это в классе Enum, используя jmockt?
- 1Обновите панель сведений с помощью нового окна управления пользователями MVVM WPF
- 0Убедитесь, что длинная строка загружена в справочную базу
- 0Angular.js, добавить строку к имени переменной?
- 1Маршалинг структуры в одну строку строки
- 0vector <shared_ptr <>> Очистить ошибку
- 0Преобразование изображения base64 в файл в javascript или как передать большую строку base64 с помощью jquery ajax
- 1Ошибка зависимости Hadoop maven — классы Hadoop не найдены
- 1Как установить содержание деятельности на основе текущей ориентации экрана?
- 0kineticJS children — Jquery, перетаскиваемый
- 1Проблемы с окном и уровнем изображения Dicom (иногда)
- 0Элементы управления C ++ для игры, запущенной в консоли Windows


