Sorry if this is a road heavily traveled. I’ve seen the other posts about this but nothing in them has either solved the problem I’m having or ignited a lightbulb that helped me solve it myself.
Here’s my code:
require 'PHPMailerAutoload.php';
$config = parse_ini_file('/path/to/file/config.ini', true);
$mail = new PHPMailer;
$mail->SMTPDebug = 3;
$mail->Debugoutput = 'html';
$mail->isSMTP();
$mail->Host = $config['host']; //smtp.office365.com
$mail->SMTPAuth = true;
$mail->Username = $config['username']; //an.existing.account@appinc.co
$mail->Password = $config['password']; //confirmed this is being passed correctly
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->From = $config['username'];
$mail->FromName = 'Website Forms';
$mail->addAddress('sales@appinc.co', 'Some Name');
$mail->addReplyTo('sender.email@somedomain.com', 'SenderFirst SenderLast');
$mail->addBCC('my.email.address@appinc.co');
$mail->isHTML(true);
$mail->Subject = 'Contact Form Submission';
$mail->Body = 'Some html here';
$mail->AltBody = 'Some alt content here';
if(!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
//perform success actions
exit();
}
I’ve confirmed that the domain, username and password are all correct and being passed in correctly. Important to note that this worked on our local dev server prior to launch. Once the site was moved to our hosting account (Hostgator) is when it stopped working. I’ve confirmed with HG that port 587 is open on our server.
Here is the error message I’m seeing:
Connection: opening to smtp.office365.com:587, t=10, opt=array ()
SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP connect() failed.
Message could not be sent.Mailer Error: SMTP connect() failed.
Any help that can be provided is very much appreciated, even if it’s just a link to an article that explains why it won’t work now that it’s in our production environment.
Извините, если это дорога, по которой много ездили. Я видел другие посты об этом, но ничто в них не решило проблему, которую я имею, или зажгло лампочку, которая помогла мне решить это самостоятельно.
Вот мой код:
require 'PHPMailerAutoload.php';
$config = parse_ini_file('/path/to/file/config.ini', true);
$mail = new PHPMailer;
$mail->SMTPDebug = 3;
$mail->Debugoutput = 'html';
$mail->isSMTP();
$mail->Host = $config['host']; //smtp.office365.com
$mail->SMTPAuth = true;
$mail->Username = $config['username']; //an.existing.account@appinc.co
$mail->Password = $config['password']; //confirmed this is being passed correctly
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->From = $config['username'];
$mail->FromName = 'Website Forms';
$mail->addAddress('sales@appinc.co', 'Some Name');
$mail->addReplyTo('sender.email@somedomain.com', 'SenderFirst SenderLast');
$mail->addBCC('my.email.address@appinc.co');
$mail->isHTML(true);
$mail->Subject = 'Contact Form Submission';
$mail->Body = 'Some html here';
$mail->AltBody = 'Some alt content here';
if(!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
//perform success actions
exit();
}
Я подтвердил, что домен, имя пользователя и пароль верны и передаются правильно. Важно отметить, что это работало на нашем локальном сервере разработчика до запуска. Как только сайт был перенесен на наш хостинг-аккаунт (Hostgator), это когда он перестал работать. Я подтвердил с помощью HG, что порт 587 открыт на нашем сервере.
Вот сообщение об ошибке, которое я вижу:
Connection: opening to smtp.office365.com:587, t=10, opt=array ()
SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP connect() failed.
Message could not be sent.Mailer Error: SMTP connect() failed.
Любая помощь, которая может быть оказана, очень ценится, даже если это просто ссылка на статью, которая объясняет, почему она не будет работать сейчас, когда она находится в нашей производственной среде.
8
Решение
Ни один из ответов не сработал для меня.
Через много часов я нашел проблему, но работает только для Cpanel / WHM
- Войдите в WHM.
- Перейти к ConfigServer Security & Брандмауэр внутри плагина опция.
- Нажмите на настройку брандмауэра
- Фильтр по настройкам SMTP
- Найдите параметр SMTP_ALLOWUSER и добавьте имя пользователя учетной записи Cpanel, разделенное комой.
- Перезагрузите брандмауэр.
Если у вас нет доступа к WHM, обратитесь к своему провайдеру.
6
Другие решения
В PHP 5.5 и phpmailer есть ошибка с номером порта. Не устанавливайте номер порта (mail-> port = ….), это вызывает ошибку:
msgstr «ошибка smtp не удалось установить соединение с сервером отказано 111»
Оставьте номер порта по умолчанию 25, и он будет работать!
2
Оказывается, HG нужно было изменить настройки брандмауэра на нашем сервере. Как только они это сделали, все заработало отлично. Так что, если у вас возникла подобная проблема, я бы порекомендовал убедиться, что все правильно с вашей стороны, но затем посоветуйтесь с вашим хостинг-провайдером, чтобы узнать, что нужно сделать с их стороны.
0
Если вы используете cPanel / WHM, вам необходимо убедиться, что:
Ограничить исходящий SMTP для root, exim и mailman (FKA SMTP Tweak) — установлен в OFF. (Это можно отредактировать в разделе «Конфигурация сервера» Настройки твика (поиск: SMTP))
Если у вас также есть ConfigServer Security & Брандмауэр включен, вам нужно будет изменить конфигурацию брандмауэра. Нажмите «Настройка брандмауэра», затем выберите «Фильтровать по настройкам SMTP». Теперь найдите SMTP_ALLOWUSER и добавьте имя пользователя учетной записи cPanel, разделенное комой. Нажмите «Изменить» и перезапустите брандмауэр.
0
Есть 3 сервера.
1 mailwizz -web программа для отправки писем
2 mailwizz -web программа для отправки писем
3 почтовый сервер
оба mailwiz — по конфигурации вроде как идентичны
на почтовом сервере 587 порт открыт, ограничений на mailwizz сервера нет, все в порядке
mailwizz,ы подключаются к почтовому серверу через smtp
почтовым сервером управляет PMTA, сертификаты настроены — другой майлвиз шлет
проблема:
1 mailwizz — прекрасно коннектится по 587 к почтовому серверу и шлет письма
2 mailwizz — не как не хочет, пишет ошибку
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Connection: opening to m-spf.ru:587, timeout=30, options=array ( 'ssl' => array ( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true, ),)
Connection failed. Error #2: stream_socket_client(): unable to connect to postal.ru:587 (Connection refused) [/var/www/mailwizz/data/www/mailwizz.ru/apps/common/vendors/Composer/vendor/phpmailer/phpmailer/src/SMTP.php line 387]
SMTP ERROR: Failed to connect to server: Connection refused (111)
на проблемном сервере mailwizz
— панель isp manager
— PHP Version 7.3.19
— SSL Version OpenSSL/1.0.2u
openssl
OpenSSL support enabled
OpenSSL Library Version OpenSSL 1.1.0l 10 Sep 2019
OpenSSL Header Version OpenSSL 1.1.0l 10 Sep 2019
Openssl default config /usr/lib/ssl/openssl.cnf
Native OpenSSL support enabled
все что про него знаю, вроде тоже самое что на другом mailwizz
Как можно мой майлвиз подружить с 587 портом моего почтового сервера.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
<?php /** * SendMailSmtpClass * * Класс для отправки писем через SMTP с авторизацией * Может работать через SSL протокол * Тестировалось на почтовых серверах yandex.ru, mail.ru и gmail.com * * @author Ipatov Evgeniy <admin@ipatov-soft.ru> * @version 1.0 */ class SendMailSmtpClass { /** * * @var string $smtp_username - логин * @var string $smtp_password - пароль * @var string $smtp_host - хост * @var string $smtp_from - от кого * @var integer $smtp_port - порт * @var string $smtp_charset - кодировка * */ public $smtp_username; public $smtp_password; public $smtp_host; public $smtp_from; public $smtp_port; public $smtp_charset; public function __construct($smtp_username, $smtp_password, $smtp_host, $smtp_from, $smtp_port = 25, $smtp_charset = "utf-8") { $this->smtp_username = $smtp_username; $this->smtp_password = $smtp_password; $this->smtp_host = $smtp_host; $this->smtp_from = $smtp_from; $this->smtp_port = $smtp_port; $this->smtp_charset = $smtp_charset; } /** * Отправка письма * * @param string $mailTo - получатель письма * @param string $subject - тема письма * @param string $message - тело письма * @param string $headers - заголовки письма * * @return bool|string В случаи отправки вернет true, иначе текст ошибки * */ function send($mailTo, $subject, $message, $headers) { $contentMail = "Date: " . date("D, d M Y H:i:s") . " UTrn"; $contentMail .= 'Subject: =?' . $this->smtp_charset . '?B?' . base64_encode($subject) . "=?=rn"; $contentMail .= $headers . "rn"; $contentMail .= $message . "rn"; try { if(!$socket = @fsockopen($this->smtp_host, $this->smtp_port, $errorNumber, $errorDescription, 30)){ throw new Exception($errorNumber.".".$errorDescription); } if (!$this->_parseServer($socket, "220")){ throw new Exception('Connection error'); } $server_name = $_SERVER["SERVER_NAME"]; fputs($socket, "HELO $server_namern"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception('Error of command sending: HELO'); } fputs($socket, "AUTH LOGINrn"); if (!$this->_parseServer($socket, "334")) { fclose($socket); throw new Exception('Autorization error'); } fputs($socket, base64_encode($this->smtp_username) . "rn"); if (!$this->_parseServer($socket, "334")) { fclose($socket); throw new Exception('Autorization error'); } fputs($socket, base64_encode($this->smtp_password) . "rn"); if (!$this->_parseServer($socket, "235")) { fclose($socket); throw new Exception('Autorization error'); } fputs($socket, "MAIL FROM: <".$this->smtp_username.">rn"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception('Error of command sending: MAIL FROM'); } $mailTo = ltrim($mailTo, '<'); $mailTo = rtrim($mailTo, '>'); fputs($socket, "RCPT TO: <" . $mailTo . ">rn"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception('Error of command sending: RCPT TO'); } fputs($socket, "DATArn"); if (!$this->_parseServer($socket, "354")) { fclose($socket); throw new Exception('Error of command sending: DATA'); } fputs($socket, $contentMail."rn.rn"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception("E-mail didn't sent"); } fputs($socket, "QUITrn"); fclose($socket); } catch (Exception $e) { return $e->getMessage(); } return true; } private function _parseServer($socket, $response) { while (@substr($responseServer, 3, 1) != ' ') { if (!($responseServer = fgets($socket, 256))) { return false; } } if (!(substr($responseServer, 0, 3) == $response)) { return false; } return true; } } |
Sometimes users need to send outgoing e-mails with external SMTP servers. Most popular example is PHPMailer with its ability to use free SMTP servers, for example Gmail. Here is the short piece of code, that allows to do this:
<?php use PHPMailerPHPMailerPHPMailer; use PHPMailerPHPMailerException; require './mail/PHPMailer-master/src/Exception.php'; require './PHPMailer-master/src/PHPMailer.php'; require './mail/PHPMailer-master/src/SMTP.php'; date_default_timezone_set('Etc/UTC'); $milo="this is a test"; /** * This example shows sending a message using PHP's mail() function. */ //Create a new PHPMailer instance $mail = new PHPMailer; //Tell PHPMailer to use SMTP $mail->isSMTP(); $mail->SMTPDebug = 0; //Set who the message is to be sent from $mail->setFrom('example@gmail.com', 'First Last'); //Set who the message is to be sent to $mail->addAddress('support@example.com', 'John Doe'); //Set the subject line $mail->Subject = 'PHPMailer test 2 smtp'; $mail->CharSet = 'UTF-8'; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; $mail->SMTPSecure = 'tls'; $mail->Host = 'smtp.gmail.com'; $mail->Port = 587; //Whether to use SMTP authentication $mail->SMTPAuth = true; //Username to use for SMTP authentication $mail->Username = "example@gmail.com"; //Password to use for SMTP authentication $mail->Password = "yourpassword"; $mail->msgHTML($milo); //Replace the plain text body with one created manually $mail->AltBody = $milo; //send the message, check for errors if (!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message sent!"; } ?>
If you have a Directadmin server with csf firewall installed, most probably you will get this message on execution:
SMTP ERROR: Failed to connect to server: Connection refused (111)
Let’s investigate what causes this error. First, we need to change debug level in our script to get all error messages:
$mail->SMTPDebug = 4;
Here is what we are getting:
2018-03-29 13:01:34 Connection: opening to smtp.gmail.com:587, timeout=300, options=array() 2018-03-29 13:01:37 Connection failed. Error #2: stream_socket_client(): unable to connect to smtp.gmail.com:587 (Connection refused) [SMTP.php line 326] 2018-03-29 13:01:37 SMTP ERROR: Failed to connect to server: Connection refused (111) SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
So the problem seems to be with opening port 587 – the script is even unable to connect. Let’s verify if we have this port blocked by firewall:
[root@server ~]# dmesg | grep 587
Most probably our output will look like this:
Firewall: *TCP_OUT Blocked* IN= OUT=eth0 SRC=62.210.90.101 DST=66.102.1.109 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=57285 DF PROTO=TCP SPT=50856 DPT=587 WINDOW=14600 RES=0x00 SYN URGP=0 UID=503 GID=505 Firewall: *TCP6OUT Blocked* IN= OUT=eth0 SRC=fe80:0000:0000:0000:fabc:12ff:fe48:effa DST=2a00:1450:400c:0c06:0000:0000:0000:006d LEN=80 TC=0 HOPLIMIT=64 FLOWLBL=0 PROTO=TCP SPT=45138 DPT=587 WINDOW=14400 RES=0x00 SYN URGP=0 UID=503 GID=505 Firewall: *TCP6OUT Blocked* IN= OUT=eth0 SRC=fe80:0000:0000:0000:fabc:12ff:fe48:effa DST=2a00:1450:400c:0c06:0000:0000:0000:006d LEN=80 TC=0 HOPLIMIT=64 FLOWLBL=0 PROTO=TCP SPT=45138 DPT=587 WINDOW=14400 RES=0x00 SYN URGP=0 UID=503 GID=505
Here’s the catch – our firewall is blocking outgoing connection through this port. We need to unlock it to continue. Here is the solution.
Open /etc/csf/csf.conf in any editor
Scroll to this line:
SMTP_BLOCK = "1"
Change it to
SMTP_BLOCK = "0"
Restart csf:
csf -r
Now you should be able to use your script without any issues.
What’s Causing This Error
The SMTP 111 error occurs when an issue is present while connecting with the remote SMTP server. For example, you would run into this error due to invalid sender domains or firewall issues.
Additionally, with some mail servers (Amazon SES in particular), you may encounter the 111 error due to invalid login credentials or if the email sending port gets blocked by the recipient.
Solution — Here’s How To Resolve It
First, ensure that the email address to which you’re sending the email is spelled correctly (especially the domain name). For example, if you’re sending the email to a Gmail domain, ensure that the domain is «gmail.com.»
Then, ensure that you’ve provided the correct username and password for SMTP authentication.
Finally, ensure that the email sending port is available for use on your end, and ensure that the port gets accepted on the recipient’s end.
However, you can only troubleshoot the SMTP server for firewall issues if the error persists by connecting to the recipient SMTP server through your local computer. If you cannot connect to the server through your local computer, the issue may likely occur on the recipient’s end. Therefore you may have to contact the recipient for more information.
Есть 3 сервера.
1 mailwizz -web программа для отправки писем
2 mailwizz -web программа для отправки писем
3 почтовый сервер
оба mailwiz — по конфигурации вроде как идентичны
на почтовом сервере 587 порт открыт, ограничений на mailwizz сервера нет, все в порядке
mailwizz,ы подключаются к почтовому серверу через smtp
почтовым сервером управляет PMTA, сертификаты настроены — другой майлвиз шлет
проблема:
1 mailwizz — прекрасно коннектится по 587 к почтовому серверу и шлет письма
2 mailwizz — не как не хочет, пишет ошибку
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Connection: opening to m-spf.ru:587, timeout=30, options=array ( 'ssl' => array ( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true, ),)
Connection failed. Error #2: stream_socket_client(): unable to connect to postal.ru:587 (Connection refused) [/var/www/mailwizz/data/www/mailwizz.ru/apps/common/vendors/Composer/vendor/phpmailer/phpmailer/src/SMTP.php line 387]
SMTP ERROR: Failed to connect to server: Connection refused (111)
на проблемном сервере mailwizz
— панель isp manager
— PHP Version 7.3.19
— SSL Version OpenSSL/1.0.2u
openssl
OpenSSL support enabled
OpenSSL Library Version OpenSSL 1.1.0l 10 Sep 2019
OpenSSL Header Version OpenSSL 1.1.0l 10 Sep 2019
Openssl default config /usr/lib/ssl/openssl.cnf
Native OpenSSL support enabled
все что про него знаю, вроде тоже самое что на другом mailwizz
Как можно мой майлвиз подружить с 587 портом моего почтового сервера.
What’s Causing This Error
The SMTP 111 error occurs when an issue is present while connecting with the remote SMTP server. For example, you would run into this error due to invalid sender domains or firewall issues.
Additionally, with some mail servers (Amazon SES in particular), you may encounter the 111 error due to invalid login credentials or if the email sending port gets blocked by the recipient.
Solution — Here’s How To Resolve It
First, ensure that the email address to which you’re sending the email is spelled correctly (especially the domain name). For example, if you’re sending the email to a Gmail domain, ensure that the domain is «gmail.com.»
Then, ensure that you’ve provided the correct username and password for SMTP authentication.
Finally, ensure that the email sending port is available for use on your end, and ensure that the port gets accepted on the recipient’s end.
However, you can only troubleshoot the SMTP server for firewall issues if the error persists by connecting to the recipient SMTP server through your local computer. If you cannot connect to the server through your local computer, the issue may likely occur on the recipient’s end. Therefore you may have to contact the recipient for more information.
Извините, если это дорога, по которой много ездили. Я видел другие посты об этом, но ничто в них не решило проблему, которую я имею, или зажгло лампочку, которая помогла мне решить это самостоятельно.
Вот мой код:
require 'PHPMailerAutoload.php';
$config = parse_ini_file('/path/to/file/config.ini', true);
$mail = new PHPMailer;
$mail->SMTPDebug = 3;
$mail->Debugoutput = 'html';
$mail->isSMTP();
$mail->Host = $config['host']; //smtp.office365.com
$mail->SMTPAuth = true;
$mail->Username = $config['username']; //an.existing.account@appinc.co
$mail->Password = $config['password']; //confirmed this is being passed correctly
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->From = $config['username'];
$mail->FromName = 'Website Forms';
$mail->addAddress('sales@appinc.co', 'Some Name');
$mail->addReplyTo('sender.email@somedomain.com', 'SenderFirst SenderLast');
$mail->addBCC('my.email.address@appinc.co');
$mail->isHTML(true);
$mail->Subject = 'Contact Form Submission';
$mail->Body = 'Some html here';
$mail->AltBody = 'Some alt content here';
if(!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
//perform success actions
exit();
}
Я подтвердил, что домен, имя пользователя и пароль верны и передаются правильно. Важно отметить, что это работало на нашем локальном сервере разработчика до запуска. Как только сайт был перенесен на наш хостинг-аккаунт (Hostgator), это когда он перестал работать. Я подтвердил с помощью HG, что порт 587 открыт на нашем сервере.
Вот сообщение об ошибке, которое я вижу:
Connection: opening to smtp.office365.com:587, t=10, opt=array ()
SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP connect() failed.
Message could not be sent.Mailer Error: SMTP connect() failed.
Любая помощь, которая может быть оказана, очень ценится, даже если это просто ссылка на статью, которая объясняет, почему она не будет работать сейчас, когда она находится в нашей производственной среде.
8
Решение
Ни один из ответов не сработал для меня.
Через много часов я нашел проблему, но работает только для Cpanel / WHM
- Войдите в WHM.
- Перейти к ConfigServer Security & Брандмауэр внутри плагина опция.
- Нажмите на настройку брандмауэра
- Фильтр по настройкам SMTP
- Найдите параметр SMTP_ALLOWUSER и добавьте имя пользователя учетной записи Cpanel, разделенное комой.
- Перезагрузите брандмауэр.
Если у вас нет доступа к WHM, обратитесь к своему провайдеру.
6
Другие решения
В PHP 5.5 и phpmailer есть ошибка с номером порта. Не устанавливайте номер порта (mail-> port = ….), это вызывает ошибку:
msgstr «ошибка smtp не удалось установить соединение с сервером отказано 111»
Оставьте номер порта по умолчанию 25, и он будет работать!
2
Оказывается, HG нужно было изменить настройки брандмауэра на нашем сервере. Как только они это сделали, все заработало отлично. Так что, если у вас возникла подобная проблема, я бы порекомендовал убедиться, что все правильно с вашей стороны, но затем посоветуйтесь с вашим хостинг-провайдером, чтобы узнать, что нужно сделать с их стороны.
0
Если вы используете cPanel / WHM, вам необходимо убедиться, что:
Ограничить исходящий SMTP для root, exim и mailman (FKA SMTP Tweak) — установлен в OFF. (Это можно отредактировать в разделе «Конфигурация сервера» Настройки твика (поиск: SMTP))
Если у вас также есть ConfigServer Security & Брандмауэр включен, вам нужно будет изменить конфигурацию брандмауэра. Нажмите «Настройка брандмауэра», затем выберите «Фильтровать по настройкам SMTP». Теперь найдите SMTP_ALLOWUSER и добавьте имя пользователя учетной записи cPanel, разделенное комой. Нажмите «Изменить» и перезапустите брандмауэр.
0
Есть 3 сервера.
1 mailwizz -web программа для отправки писем
2 mailwizz -web программа для отправки писем
3 почтовый сервер
оба mailwiz — по конфигурации вроде как идентичны
на почтовом сервере 587 порт открыт, ограничений на mailwizz сервера нет, все в порядке
mailwizz,ы подключаются к почтовому серверу через smtp
почтовым сервером управляет PMTA, сертификаты настроены — другой майлвиз шлет
проблема:
1 mailwizz — прекрасно коннектится по 587 к почтовому серверу и шлет письма
2 mailwizz — не как не хочет, пишет ошибку
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Connection: opening to m-spf.ru:587, timeout=30, options=array ( 'ssl' => array ( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true, ),)
Connection failed. Error #2: stream_socket_client(): unable to connect to postal.ru:587 (Connection refused) [/var/www/mailwizz/data/www/mailwizz.ru/apps/common/vendors/Composer/vendor/phpmailer/phpmailer/src/SMTP.php line 387]
SMTP ERROR: Failed to connect to server: Connection refused (111)
на проблемном сервере mailwizz
— панель isp manager
— PHP Version 7.3.19
— SSL Version OpenSSL/1.0.2u
openssl
OpenSSL support enabled
OpenSSL Library Version OpenSSL 1.1.0l 10 Sep 2019
OpenSSL Header Version OpenSSL 1.1.0l 10 Sep 2019
Openssl default config /usr/lib/ssl/openssl.cnf
Native OpenSSL support enabled
все что про него знаю, вроде тоже самое что на другом mailwizz
Как можно мой майлвиз подружить с 587 портом моего почтового сервера.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
<?php /** * SendMailSmtpClass * * Класс для отправки писем через SMTP с авторизацией * Может работать через SSL протокол * Тестировалось на почтовых серверах yandex.ru, mail.ru и gmail.com * * @author Ipatov Evgeniy <admin@ipatov-soft.ru> * @version 1.0 */ class SendMailSmtpClass { /** * * @var string $smtp_username - логин * @var string $smtp_password - пароль * @var string $smtp_host - хост * @var string $smtp_from - от кого * @var integer $smtp_port - порт * @var string $smtp_charset - кодировка * */ public $smtp_username; public $smtp_password; public $smtp_host; public $smtp_from; public $smtp_port; public $smtp_charset; public function __construct($smtp_username, $smtp_password, $smtp_host, $smtp_from, $smtp_port = 25, $smtp_charset = "utf-8") { $this->smtp_username = $smtp_username; $this->smtp_password = $smtp_password; $this->smtp_host = $smtp_host; $this->smtp_from = $smtp_from; $this->smtp_port = $smtp_port; $this->smtp_charset = $smtp_charset; } /** * Отправка письма * * @param string $mailTo - получатель письма * @param string $subject - тема письма * @param string $message - тело письма * @param string $headers - заголовки письма * * @return bool|string В случаи отправки вернет true, иначе текст ошибки * */ function send($mailTo, $subject, $message, $headers) { $contentMail = "Date: " . date("D, d M Y H:i:s") . " UTrn"; $contentMail .= 'Subject: =?' . $this->smtp_charset . '?B?' . base64_encode($subject) . "=?=rn"; $contentMail .= $headers . "rn"; $contentMail .= $message . "rn"; try { if(!$socket = @fsockopen($this->smtp_host, $this->smtp_port, $errorNumber, $errorDescription, 30)){ throw new Exception($errorNumber.".".$errorDescription); } if (!$this->_parseServer($socket, "220")){ throw new Exception('Connection error'); } $server_name = $_SERVER["SERVER_NAME"]; fputs($socket, "HELO $server_namern"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception('Error of command sending: HELO'); } fputs($socket, "AUTH LOGINrn"); if (!$this->_parseServer($socket, "334")) { fclose($socket); throw new Exception('Autorization error'); } fputs($socket, base64_encode($this->smtp_username) . "rn"); if (!$this->_parseServer($socket, "334")) { fclose($socket); throw new Exception('Autorization error'); } fputs($socket, base64_encode($this->smtp_password) . "rn"); if (!$this->_parseServer($socket, "235")) { fclose($socket); throw new Exception('Autorization error'); } fputs($socket, "MAIL FROM: <".$this->smtp_username.">rn"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception('Error of command sending: MAIL FROM'); } $mailTo = ltrim($mailTo, '<'); $mailTo = rtrim($mailTo, '>'); fputs($socket, "RCPT TO: <" . $mailTo . ">rn"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception('Error of command sending: RCPT TO'); } fputs($socket, "DATArn"); if (!$this->_parseServer($socket, "354")) { fclose($socket); throw new Exception('Error of command sending: DATA'); } fputs($socket, $contentMail."rn.rn"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception("E-mail didn't sent"); } fputs($socket, "QUITrn"); fclose($socket); } catch (Exception $e) { return $e->getMessage(); } return true; } private function _parseServer($socket, $response) { while (@substr($responseServer, 3, 1) != ' ') { if (!($responseServer = fgets($socket, 256))) { return false; } } if (!(substr($responseServer, 0, 3) == $response)) { return false; } return true; } } |
Sometimes users need to send outgoing e-mails with external SMTP servers. Most popular example is PHPMailer with its ability to use free SMTP servers, for example Gmail. Here is the short piece of code, that allows to do this:
<?php use PHPMailerPHPMailerPHPMailer; use PHPMailerPHPMailerException; require './mail/PHPMailer-master/src/Exception.php'; require './PHPMailer-master/src/PHPMailer.php'; require './mail/PHPMailer-master/src/SMTP.php'; date_default_timezone_set('Etc/UTC'); $milo="this is a test"; /** * This example shows sending a message using PHP's mail() function. */ //Create a new PHPMailer instance $mail = new PHPMailer; //Tell PHPMailer to use SMTP $mail->isSMTP(); $mail->SMTPDebug = 0; //Set who the message is to be sent from $mail->setFrom('example@gmail.com', 'First Last'); //Set who the message is to be sent to $mail->addAddress('support@example.com', 'John Doe'); //Set the subject line $mail->Subject = 'PHPMailer test 2 smtp'; $mail->CharSet = 'UTF-8'; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; $mail->SMTPSecure = 'tls'; $mail->Host = 'smtp.gmail.com'; $mail->Port = 587; //Whether to use SMTP authentication $mail->SMTPAuth = true; //Username to use for SMTP authentication $mail->Username = "example@gmail.com"; //Password to use for SMTP authentication $mail->Password = "yourpassword"; $mail->msgHTML($milo); //Replace the plain text body with one created manually $mail->AltBody = $milo; //send the message, check for errors if (!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message sent!"; } ?>
If you have a Directadmin server with csf firewall installed, most probably you will get this message on execution:
SMTP ERROR: Failed to connect to server: Connection refused (111)
Let’s investigate what causes this error. First, we need to change debug level in our script to get all error messages:
$mail->SMTPDebug = 4;
Here is what we are getting:
2018-03-29 13:01:34 Connection: opening to smtp.gmail.com:587, timeout=300, options=array() 2018-03-29 13:01:37 Connection failed. Error #2: stream_socket_client(): unable to connect to smtp.gmail.com:587 (Connection refused) [SMTP.php line 326] 2018-03-29 13:01:37 SMTP ERROR: Failed to connect to server: Connection refused (111) SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
So the problem seems to be with opening port 587 – the script is even unable to connect. Let’s verify if we have this port blocked by firewall:
[root@server ~]# dmesg | grep 587
Most probably our output will look like this:
Firewall: *TCP_OUT Blocked* IN= OUT=eth0 SRC=62.210.90.101 DST=66.102.1.109 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=57285 DF PROTO=TCP SPT=50856 DPT=587 WINDOW=14600 RES=0x00 SYN URGP=0 UID=503 GID=505 Firewall: *TCP6OUT Blocked* IN= OUT=eth0 SRC=fe80:0000:0000:0000:fabc:12ff:fe48:effa DST=2a00:1450:400c:0c06:0000:0000:0000:006d LEN=80 TC=0 HOPLIMIT=64 FLOWLBL=0 PROTO=TCP SPT=45138 DPT=587 WINDOW=14400 RES=0x00 SYN URGP=0 UID=503 GID=505 Firewall: *TCP6OUT Blocked* IN= OUT=eth0 SRC=fe80:0000:0000:0000:fabc:12ff:fe48:effa DST=2a00:1450:400c:0c06:0000:0000:0000:006d LEN=80 TC=0 HOPLIMIT=64 FLOWLBL=0 PROTO=TCP SPT=45138 DPT=587 WINDOW=14400 RES=0x00 SYN URGP=0 UID=503 GID=505
Here’s the catch – our firewall is blocking outgoing connection through this port. We need to unlock it to continue. Here is the solution.
Open /etc/csf/csf.conf in any editor
Scroll to this line:
SMTP_BLOCK = "1"
Change it to
SMTP_BLOCK = "0"
Restart csf:
csf -r
Now you should be able to use your script without any issues.
Ошибки при подключении почты и отправке сообщений
Содержание:
- Ошибки при подключении почты
- Ошибки при отправке сообщений
Ошибки при подключении почты
При сохранении почтового канала при внешнем типе соединения (imap/smtp) Юздеск производит попытку соединения. Если попытка оказывается неудачной, система выводит красную плашку с номером ошибки:
Возможные ошибки:
- Ошибка 101: Сервер не отвечает или недоступен.
- Ошибка 111: Не получается установить соединение по протоколу SMTP.
- Ошибка 420: Сервер не отвечает или недоступен. Сервер долго не отвечает при запросе.
- Ошибка 422: Почтовый ящик получателя переполнен.
- Ошибка 441: Почтовый сервер получателя не отвечает.
- Ошибка 450: Почтовый сервер получателя не отвечает. По какой-то причине недоступен почтовый сервер получателя. Возможно, он не существует.
- Ошибка 500: Почтовый сервер получателя не отвечает. Ошибка возникает, когда почтовый сервер не понимает запрос из-за разных операционных систем, либо допущена ошибка в запросе.
- Ошибка 510: Некорректный адрес получателя.
- Ошибка 512: Домен получателя не существует.
- Ошибка 530: Неверный логин или пароль. Неверный логин или пароль, либо пользователю не выданы нужные права доступа.
Ошибки при отправке сообщений
При ошибке отправки сообщения оно станет внутренним комментарием на красном фоне. В правом верхнем углу появится сообщение об ошибке — оно либо пояснит причину ошибки, либо предложит написать нам в поддержку для решения вопроса. Возможные типы ошибок:
- Не удалось отправить сообщение. Пожалуйста, напишите нам на support@usedesk.ru;
- Неверный адрес отправителя. Пожалуйста, проверьте, нет ли ошибки в почтовом адресе отправителя;
- Неверный адрес получателя. Пожалуйста, проверьте, нет ли ошибки в почтовом адресе получателя;
- Ошибка при обработке текста сообщения. Пожалуйста, напишите нам на support@usedesk.ru;
- Неверный адрес получателя в копии. Пожалуйста, проверьте, нет ли ошибки в почтовом адресе получателя;
- Неверный адрес получателя в скрытой копии. Пожалуйста, проверьте, нет ли ошибки в почтовом адресе получателя;
- Превышено максимально допустимое число отправок microsoft graph, попробуйте позднее. Подробнее о лимитах — по ссылке.
Извините, если это дорога, по которой много ездили. Я видел другие посты об этом, но ничто в них не решило проблему, которую я имею, или зажгло лампочку, которая помогла мне решить это самостоятельно.
Вот мой код:
require 'PHPMailerAutoload.php';
$config = parse_ini_file('/path/to/file/config.ini', true);
$mail = new PHPMailer;
$mail->SMTPDebug = 3;
$mail->Debugoutput = 'html';
$mail->isSMTP();
$mail->Host = $config['host']; //smtp.office365.com
$mail->SMTPAuth = true;
$mail->Username = $config['username']; //an.existing.account@appinc.co
$mail->Password = $config['password']; //confirmed this is being passed correctly
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->From = $config['username'];
$mail->FromName = 'Website Forms';
$mail->addAddress('sales@appinc.co', 'Some Name');
$mail->addReplyTo('sender.email@somedomain.com', 'SenderFirst SenderLast');
$mail->addBCC('my.email.address@appinc.co');
$mail->isHTML(true);
$mail->Subject = 'Contact Form Submission';
$mail->Body = 'Some html here';
$mail->AltBody = 'Some alt content here';
if(!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
//perform success actions
exit();
}
Я подтвердил, что домен, имя пользователя и пароль верны и передаются правильно. Важно отметить, что это работало на нашем локальном сервере разработчика до запуска. Как только сайт был перенесен на наш хостинг-аккаунт (Hostgator), это когда он перестал работать. Я подтвердил с помощью HG, что порт 587 открыт на нашем сервере.
Вот сообщение об ошибке, которое я вижу:
Connection: opening to smtp.office365.com:587, t=10, opt=array ()
SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP connect() failed.
Message could not be sent.Mailer Error: SMTP connect() failed.
Любая помощь, которая может быть оказана, очень ценится, даже если это просто ссылка на статью, которая объясняет, почему она не будет работать сейчас, когда она находится в нашей производственной среде.
8
Решение
Ни один из ответов не сработал для меня.
Через много часов я нашел проблему, но работает только для Cpanel / WHM
- Войдите в WHM.
- Перейти к ConfigServer Security & Брандмауэр внутри плагина опция.
- Нажмите на настройку брандмауэра
- Фильтр по настройкам SMTP
- Найдите параметр SMTP_ALLOWUSER и добавьте имя пользователя учетной записи Cpanel, разделенное комой.
- Перезагрузите брандмауэр.
Если у вас нет доступа к WHM, обратитесь к своему провайдеру.
6
Другие решения
В PHP 5.5 и phpmailer есть ошибка с номером порта. Не устанавливайте номер порта (mail-> port = ….), это вызывает ошибку:
msgstr «ошибка smtp не удалось установить соединение с сервером отказано 111»
Оставьте номер порта по умолчанию 25, и он будет работать!
2
Оказывается, HG нужно было изменить настройки брандмауэра на нашем сервере. Как только они это сделали, все заработало отлично. Так что, если у вас возникла подобная проблема, я бы порекомендовал убедиться, что все правильно с вашей стороны, но затем посоветуйтесь с вашим хостинг-провайдером, чтобы узнать, что нужно сделать с их стороны.
0
Если вы используете cPanel / WHM, вам необходимо убедиться, что:
Ограничить исходящий SMTP для root, exim и mailman (FKA SMTP Tweak) — установлен в OFF. (Это можно отредактировать в разделе «Конфигурация сервера» Настройки твика (поиск: SMTP))
Если у вас также есть ConfigServer Security & Брандмауэр включен, вам нужно будет изменить конфигурацию брандмауэра. Нажмите «Настройка брандмауэра», затем выберите «Фильтровать по настройкам SMTP». Теперь найдите SMTP_ALLOWUSER и добавьте имя пользователя учетной записи cPanel, разделенное комой. Нажмите «Изменить» и перезапустите брандмауэр.
0
Description: Connection refused or inability to open an SMTP stream.
What does this mean?
This error is typically referencing a connection issue to the remove SMTP/Mail server. Often in relation to firewalls or misspelled domains.
How to fix SMTP Error 111?
As in most cases, you’ll want to ensure that the email address being sent to is spelled correctly (especially the domain name in this case). Upon confirming that is correct, attempt connecting to the remote SMTP server from a local machine (computer) other than your server to see if you are able to connect to that server. If you are unable to connect from your local machine it’s most likely an unresolvable issue at the remote (recipient) email server.
Related article: Testing Remote SMTP / Mail Server Connections
Есть 3 сервера.
1 mailwizz -web программа для отправки писем
2 mailwizz -web программа для отправки писем
3 почтовый сервер
оба mailwiz — по конфигурации вроде как идентичны
на почтовом сервере 587 порт открыт, ограничений на mailwizz сервера нет, все в порядке
mailwizz,ы подключаются к почтовому серверу через smtp
почтовым сервером управляет PMTA, сертификаты настроены — другой майлвиз шлет
проблема:
1 mailwizz — прекрасно коннектится по 587 к почтовому серверу и шлет письма
2 mailwizz — не как не хочет, пишет ошибку
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Connection: opening to m-spf.ru:587, timeout=30, options=array ( 'ssl' => array ( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true, ),)
Connection failed. Error #2: stream_socket_client(): unable to connect to postal.ru:587 (Connection refused) [/var/www/mailwizz/data/www/mailwizz.ru/apps/common/vendors/Composer/vendor/phpmailer/phpmailer/src/SMTP.php line 387]
SMTP ERROR: Failed to connect to server: Connection refused (111)
на проблемном сервере mailwizz
— панель isp manager
— PHP Version 7.3.19
— SSL Version OpenSSL/1.0.2u
openssl
OpenSSL support enabled
OpenSSL Library Version OpenSSL 1.1.0l 10 Sep 2019
OpenSSL Header Version OpenSSL 1.1.0l 10 Sep 2019
Openssl default config /usr/lib/ssl/openssl.cnf
Native OpenSSL support enabled
все что про него знаю, вроде тоже самое что на другом mailwizz
Как можно мой майлвиз подружить с 587 портом моего почтового сервера.
Код | Описание |
---|---|
1XX | |
101 | The server is unable to connect |
111 | Connection refused or inability to open an SMTP stream |
2XX | |
211 | System status message or help reply |
214 | A response to the HELP command |
220 | The server is ready |
221 | The server is closing its transmission channel, It can come with side messages like «Goodbye» or «Closing connection» |
250 | Its typical side message is «Requested mail action okay completed»: meaning that the server has transmitted a message |
251 | «User not local will forward»: the recipient’s account is not on the present server, so it will be relayed to another |
252 | The server cannot verify the user, but it will try to deliver the message anyway |
3XX | |
354 | The side message can be very cryptic («Start mail input end .»), It’s the typical response to the DATA command |
4XX | |
420 | «Timeout connection problem»: there have been issues during the message transfer |
421 | The service is unavailable due to a connection problem: it may refer to an exceeded limit of simultaneous connections, or a more general temporary problem |
422 | The recipient’s mailbox has exceeded its storage limit |
431 | Not enough space on the disk, or an «out of memory» condition due to a file overload |
432 | Typical side-message: «The recipient’s Exchange Server incoming mail queue has been stopped» |
441 | The recipient’s server is not responding |
442 | The connection was dropped during the transmission |
446 | The maximum hop count was exceeded for the message: an internal loop has occurred |
447 | Your outgoing message timed out because of issues concerning the incoming server |
449 | A routing error |
450 | «Requested action not taken – The user’s mailbox is unavailable», The mailbox has been corrupted or placed on an offline server, or your email hasn’t been accepted for IP problems or blacklisting |
451 | «Requested action aborted – Local error in processing», Your ISP’s server or the server that got a first relay from yours has encountered a connection problem |
452 | Too many emails sent or too many recipients: more in general, a server storage limit exceeded |
471 | An error of your mail server, often due to an issue of the local anti-spam filter |
5XX | |
500 | A syntax error: the server couldn’t recognize the command |
501 | Another syntax error, not in the command but in its parameters or arguments |
502 | The command is not implemented |
503 | The server has encountered a bad sequence of commands, or it requires an authentication |
504 | A command parameter is not implemented, Bad email address, Bad email address, A DNS error: the host server for the recipient’s domain name cannot be found |
513 | «Address type is incorrect»: another problem concerning address misspelling, In few cases, however, it’s related to an authentication issue |
523 | The total size of your mailing exceeds the recipient server’s limits |
530 | Normally, an authentication problem, But sometimes it’s about the recipient’s server blacklisting yours, or an invalid email address |
541 | The recipient address rejected your message: normally, it’s an error caused by an anti-spam filter |
550 | It usually defines a non-existent email address on the remote side |
551 | «User not local or invalid address – Relay denied», Meaning, if both your address and the recipient’s are not locally hosted by the server, a relay can be interrupted, 552 «Requested mail actions aborted – Exceeded storage allocation»: simply put, the recipient’s mailbox has exceeded its limits |
553 | «Requested action not taken – Mailbox name invalid», That is, there’s an incorrect email address into the recipients line |
554 | This means that the transaction has failed, It’s a permanent error and the server will not try to send the message again. |
550 5.1.1 Recipient address rejected: User unknown in virtual alias table
This is the bounce back message that is received by the sender from our server if the destination email address does not exist.
The same error message is received if the recipient has a mail loop. That is, if the recipient has set a forward to another email address and that email address is forwarded back to the original one. In this case, you need to remove the loop in order to receive the emails.
If there is a forward set for an account, and an email is sent to that account, if for some reason the forwarded email is not sent, the original sender may get the above error.
For example, abc@domain.com if forwarded to abc@dom.com, if a third user xyz@dom2.com emails to abc@domain.com, he may get the above error if the forwarded email is bounced.
550 5.1.1 Protocol error
This error code ideally suggests that the sender has used SMTP protocol instead of ESMTP, thus the outbound mail of the sender was rejected. In short, the sending client doesn’t properly communicate and makes errors in the SMTP protocol.
550 5.3.2 Service currently unavailable
The error code 5.3.2 usually means that the system is not accepting network messages. We would thus need to look outside Exchange for a connectivity problem.
The error code ideally occurs ideally for two reasons which are listed below:
-
The sending IP is blacklisted at an RBL or blacklist monitoring site. (You may verify the same by inputting the IP via this link: http://mxtoolbox.com/blacklists.aspx )
-
There is a temporary block on the IP on our Inbound server due to multiple mails from this IP. Feel free to contact our support desk for more information and regarding de-listing the same.
554 5.7.1 Service unavailable; Client host X.X.X.X blocked using zen.spamhaus.org
This is the error message that is received of the IP address of the sender is listed at zen.spamhaus.org
For further details, please check http://www.spamhaus.org/zen
OR check http://www.spamhaus.org/query/bl?ip= and contact zen.spamhaus.org to get the IP De-listed.
550 5.7.1 : Helo command rejected: You aren’t localhost
550 5.7.1 : Helo command rejected: You aren’t localhost.localdomain.
550 5.7.1 : Helo command rejected: You are not me
Our servers do not accept SMTP HELO command as HELO localhost or HELO localhost.localdomain or HELO . We accept HELO from a valid Domain Name or your computer name which is other than your domain name. Please check with your ISP or Mail administrator for this issue.
554 5.7.1 : Relay access denied
There are couple of reasons for this error while sending an email
Please contact support.
551 5.7.1 The message was rejected due to classification as Virus,Spam or high bulk ratio
This is a bounce back message that you receive when an email is classified as spam while sending out. If you feel that a genuine email is rejected as spam, you need to send the same email with the full headers and the content to our support team. That email in question will be reviewed manually.
530 5.7.0 Recipient address rejected: Authentication Required
This error comes when your sending mails to remote domain without using smtp authentication.
550 5.4.5 Recipient address rejected: Hourly domain sending quota exceeded
This is the error message that you get if your domain name exceeds the hourly quota set for the domain name. Here, the term ‘hour’ refers to the last 60 minutes.
550 5.4.6 Recipient address rejected: Hourly sending quota exceeded
This is the error message that you get if the user (that particular email address) exceeds the hourly quota set. Here, the term ‘hour’ refers to the last 60 minutes.
553 5.7.1 Sender address rejected: not owned by user user@domain.com
This is the error message that is received when you are trying to send an email as a different user.
554 5.7.1 : Recipient address rejected: USER IS SUSPENDED
This error comes if user is suspended in Control Panel.
522 5.7.1 : Recipient address rejected: Requested mail action aborted: exceeded storage allocation
This error comes if the user is overquota.
554 5.7.1 : Sender address rejected: Access denied
This error comes when the sender address is blocked on our server. Generally this is done if spam has originated from this user.
450 4.1.8 : Sender address rejected: Domain not found
Our inbound servers require that the hostname for the sender server should have valid MX or A records in order to accept emails from it. You need to contact the sending server’s email admin to add valid DNS records for his server.
450 4.7.1 Client host rejected: cannot find your reverse hostname
Our inbound servers require reverse hostname for the sender server to be present in order to accept the email. You need to contact the reverse hostname’s email admin to add the rDNS to into his server.
450 4.7.1 : Recipient address rejected: Policy Rejection- Quota Exceeded
This error comes from our incoming mail server if user is receiving excessive amounts of mails.
450 4.7.1 Recipient address rejected: Access denied
This occurs when the recipient address is invalid. i.e., not in form of user@domainname OR if the Recipient address is blocked on server.
451 4.3.5 Server configuration problem — try again later
451 4.7.1 Service unavailable — try again later;
This error most likely occurs if there is a configration error with our servers. If you encounter any of the above messages, please contact our support with the details.
452 4.5.3 Error: too many recipients
The error message is encountered when the user is exceeding the limit of more than 50 recipients in an email. The list of recipients is inclusive of To,Cc and Bcc. If you encounter the above error, reduce the number of recipients in the email and try again.
This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
<?php /** * SendMailSmtpClass * * Класс для отправки писем через SMTP с авторизацией * Может работать через SSL протокол * Тестировалось на почтовых серверах yandex.ru, mail.ru и gmail.com * * @author Ipatov Evgeniy <admin@ipatov-soft.ru> * @version 1.0 */ class SendMailSmtpClass { /** * * @var string $smtp_username - логин * @var string $smtp_password - пароль * @var string $smtp_host - хост * @var string $smtp_from - от кого * @var integer $smtp_port - порт * @var string $smtp_charset - кодировка * */ public $smtp_username; public $smtp_password; public $smtp_host; public $smtp_from; public $smtp_port; public $smtp_charset; public function __construct($smtp_username, $smtp_password, $smtp_host, $smtp_from, $smtp_port = 25, $smtp_charset = "utf-8") { $this->smtp_username = $smtp_username; $this->smtp_password = $smtp_password; $this->smtp_host = $smtp_host; $this->smtp_from = $smtp_from; $this->smtp_port = $smtp_port; $this->smtp_charset = $smtp_charset; } /** * Отправка письма * * @param string $mailTo - получатель письма * @param string $subject - тема письма * @param string $message - тело письма * @param string $headers - заголовки письма * * @return bool|string В случаи отправки вернет true, иначе текст ошибки * */ function send($mailTo, $subject, $message, $headers) { $contentMail = "Date: " . date("D, d M Y H:i:s") . " UTrn"; $contentMail .= 'Subject: =?' . $this->smtp_charset . '?B?' . base64_encode($subject) . "=?=rn"; $contentMail .= $headers . "rn"; $contentMail .= $message . "rn"; try { if(!$socket = @fsockopen($this->smtp_host, $this->smtp_port, $errorNumber, $errorDescription, 30)){ throw new Exception($errorNumber.".".$errorDescription); } if (!$this->_parseServer($socket, "220")){ throw new Exception('Connection error'); } $server_name = $_SERVER["SERVER_NAME"]; fputs($socket, "HELO $server_namern"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception('Error of command sending: HELO'); } fputs($socket, "AUTH LOGINrn"); if (!$this->_parseServer($socket, "334")) { fclose($socket); throw new Exception('Autorization error'); } fputs($socket, base64_encode($this->smtp_username) . "rn"); if (!$this->_parseServer($socket, "334")) { fclose($socket); throw new Exception('Autorization error'); } fputs($socket, base64_encode($this->smtp_password) . "rn"); if (!$this->_parseServer($socket, "235")) { fclose($socket); throw new Exception('Autorization error'); } fputs($socket, "MAIL FROM: <".$this->smtp_username.">rn"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception('Error of command sending: MAIL FROM'); } $mailTo = ltrim($mailTo, '<'); $mailTo = rtrim($mailTo, '>'); fputs($socket, "RCPT TO: <" . $mailTo . ">rn"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception('Error of command sending: RCPT TO'); } fputs($socket, "DATArn"); if (!$this->_parseServer($socket, "354")) { fclose($socket); throw new Exception('Error of command sending: DATA'); } fputs($socket, $contentMail."rn.rn"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception("E-mail didn't sent"); } fputs($socket, "QUITrn"); fclose($socket); } catch (Exception $e) { return $e->getMessage(); } return true; } private function _parseServer($socket, $response) { while (@substr($responseServer, 3, 1) != ' ') { if (!($responseServer = fgets($socket, 256))) { return false; } } if (!(substr($responseServer, 0, 3) == $response)) { return false; } return true; } } |