Error of command sending rcpt to

Ответили на вопрос 4 человека. Оцените лучшие ответы! И подпишитесь на вопрос, чтобы узнавать о появлении новых ответов.

Всем привет,
использую стандартный класс для отправки через yandex smtp, письма которые приходят:
в адресе Кому:undisclosed-recipients:;
как обойти это?

Класс отправки:

<?php
namespace module;

class SendMail {

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;
}

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;
    
}
}

Скрипт отправки

$mailSMTP = new SendMail($m, $p, 'ssl://smtp.yandex.ru', $m, 465);
$headers= "MIME-Version: 1.0rn";
$headers .= "Content-type: text/html; charset=utf-8rn";
$headers .= "From: Hello <mail@mail.com>rn";
$headers .= "Reply-To: mail@mail.comrn";
$result =  $mailSMTP->send('to@mail.com' 'Title', 'text body', $headers);

Отправка писем через SMTP с авторизацией по протоколу SSL на phpЭта статья является продолжением ранее написанной, на тему Отправка писем через SMTP с авторизацией на php. В предыдущей статье я выкладывал исходники класса, который писал для своих нужд, работа которого заключалась в отправке писем через smtp Яндекса. Но статья стала популярной и многие читатели блога, стали присылать вопросы по работе класса. Главной проблемой стала работа через протокол SSL. А в последнее время эта проблема стала возникать еще чаще, поскольку все популярные почтовые сервера перешли на работу по защищенному протоколу SSL. В связи с этим я немного дописал класс, он теперь способен работать и по SSL, обновленную версию можете скачать тут.

Обновление 13.03.2018: Класс обновился, подробнее тут: Новая версия класса SendMailSmtpClass

SMTP с авторизацией по протоколу SSL. Яндекс

Для работы с почтовым сервером Яндекс ни чего не изменилось, единственное, что при вызове класса, необходимо указывать ссылку на хост, работающий через SSL и изменился номер порта: был 25, стал 465. Выглядит код отправки теперь вот так:

// пример использования
require_once "SendMailSmtpClass.php"; // подключаем класс
 
$mailSMTP = new SendMailSmtpClass('zhenikipatov@yandex.ru', '****', 'ssl://smtp.yandex.ru', 'Evgeniy', 465);
// $mailSMTP = new SendMailSmtpClass('логин', 'пароль', 'хост', 'имя отправителя');
 
// заголовок письма
$headers= "MIME-Version: 1.0rn";
$headers .= "Content-type: text/html; charset=utf-8rn"; // кодировка письма
$headers .= "From: Evgeniy <admin@vk-book.ru>rn"; // от кого письмо
$result =  $mailSMTP->send('zhenikipatov@yandex.ru', 'Тема письма', 'Текст письма', $headers); // отправляем письмо
// $result =  $mailSMTP->send('Кому письмо', 'Тема письма', 'Текст письма', 'Заголовки письма');
if($result === true){
    echo "Письмо успешно отправлено";
}else{
    echo "Письмо не отправлено. Ошибка: " . $result;
}

SMTP с авторизацией по протоколу SSL. Майл

Для работы с почтовым сервером Mail.ru обновленный класс тоже подходит, как и в случае я Яндексом, тут необходимо также указать ссылку на хост с ssl и ображаться к порту 465.
Помимо этого, для корректной работы с Mail.ru в заголовках письма необходимо указывать отправителя, точно такого же с которого происходит авторизация на сервере или e-mail отправителя не указывать вовсе.
Код отправки письма через почтовый сервер Mail.ru выглядит вот так:

// пример использования
require_once "SendMailSmtpClass.php"; // подключаем класс
 
$mailSMTP = new SendMailSmtpClass('ipatovsoft@mail.ru', '****', 'ssl://smtp.mail.ru', 'Evgeniy', 465); // создаем экземпляр класса
// $mailSMTP = new SendMailSmtpClass('логин', 'пароль', 'хост', 'имя отправителя');
 
// заголовок письма
$headers= "MIME-Version: 1.0rn";
$headers .= "Content-type: text/html; charset=utf-8rn"; // кодировка письма
$headers .= "From: Evgeniy <ipatovsoft@mail.ru>rn"; // от кого письмо !!! тут e-mail, через который происходит авторизация
$result =  $mailSMTP->send('zhenikipatov@yandex.ru', 'Тема письма', 'Текст письма', $headers); // отправляем письмо
// $result =  $mailSMTP->send('Кому письмо', 'Тема письма', 'Текст письма', 'Заголовки письма');
if($result === true){
    echo "Письмо успешно отправлено";
}else{
    echo "Письмо не отправлено. Ошибка: " . $result;
}

SMTP с авторизацией по протоколу SSL. Gmail

Для работы с почтовым сервером gmail.com, необходимо указывать ссылку на хост, работающий через SSL и номер порта 465. Выглядит код отправки теперь вот так:

// пример использования
require_once "SendMailSmtpClass.php"; // подключаем класс

$mailSMTP = new SendMailSmtpClass('ipatovsoft@gmail.com', '*****', 'ssl://smtp.gmail.com', 'Evgeniy', 465); // создаем экземпляр класса
// $mailSMTP = new SendMailSmtpClass('логин', 'пароль', 'хост', 'имя отправителя');
 
// заголовок письма
$headers= "MIME-Version: 1.0rn";
$headers .= "Content-type: text/html; charset=utf-8rn"; // кодировка письма
$headers .= "From: Evgeniy <ipatovsoft@gmail.com>rn"; // от кого письмо
$result =  $mailSMTP->send('zhenikipatov@yandex.ru', 'gmail', 'Текст письма', $headers); // отправляем письмо
// $result =  $mailSMTP->send('Кому письмо', 'Тема письма', 'Текст письма', 'Заголовки письма');
if($result === true){
    echo "Письмо успешно отправлено";
}else{
    echo "Письмо не отправлено. Ошибка: " . $result;
}

На этом пока все, жду комментариев о работе обновленного класса.

Дополнения

19.10.2014 Иван Ткаченко подсказал, что можно расширить возможности класса и отправлять письмо сразу нескольким получателям, за это ему большое спасибо!
Для отправки нескольким получателям через «,» заменить
Это:

fputs($socket, "RCPT TO: rn");
    if (!$this->_parseServer($socket, "250")) {
    fclose($socket);
    throw new Exception('Error of command sending: RCPT TO');
}

На это:

$email_to_array = explode(',', $mailTo);
    foreach($email_to_array as $key => $email) {
    $emails = ltrim($email, '');
    fputs($socket, "RCPT TO: <$emails>rn");
    if (!$this->_parseServer($socket, "250")) {
        fclose($socket);
        throw new Exception('Error of command sending: RCPT TO');
    }
}

05.08.2016 Сегодня в комментарии подсказали по поводу проблемы с кодировкой, спасибо за это Евгению:
«Для тех у кого в теле и сабже полученного письма кракозябры — проверьте кодировку сервера по умолчанию и кодировку в которой написан сам скрипт. У меня windows-1251 так что прежде чем вызывать метод send использую»

$from_user=iconv("windows-1251", "utf-8" ,$from_user);
$subject =iconv("windows-1251", "utf-8" , $subject);
$message =iconv("windows-1251", "utf-8" , $message);

22.11.2016 Сегодня в комментарий добавили полезный код, который позволяет отправлять, с помощью класса, не только текст, но и файлы. Спасибо большое, за этот код Анжелике. Ниже код:

можно отправлять не только одно письмо но и файлы прикреплять к письму:
// пример использования
require_once «SendMailSmtpClass.php»; // подключаем класс

$mailSMTP = new SendMailSmtpClass(‘xxx@mail.ru’, ‘xxx’, ‘ssl://smtp.mail.ru’, ‘NameSender’, 465); // создаем экземпляр класса
// $mailSMTP = new SendMailSmtpClass(‘логин’, ‘пароль’, ‘хост’, ‘имя отправителя’);

// заголовок письма
$headers= «MIME-Version: 1.0rn»;
//$headers .= «Content-type: text/html; charset=utf-8rn»; // кодировка письма
//$headers .= «From: Anjelika rn»; // от кого письмо !!! тут e-mail, через который происходит авторизация

$subject = «пробуем отправить файл»;
$message =»Сообщение в теле письма при отправке файла»; // текст сообщения, здесь вы можете вставлять таблицы, рисунки, заголовки, оформление цветом и т.п.
$filename = «имя файла например формата.zip»; // название файла
$filepath = «./sending/полный путь к файлу.zip»; // месторасположение файла
//исьмо с вложением состоит из нескольких частей, которые разделяются разделителем
$boundary = «—-«.md5(uniqid(time())); // генерируем разделитель
$headers .= «Content-Type: multipart/mixed; boundary=»$boundary»rn»; // кодировка письма// разделитель указывается в заголовке в параметре boundary
$headers .= «From: NameSender rn»;
$multipart = «—$boundaryrn»;
$multipart .= «Content-Type: text/html; charset=windows-1251rn»;
$multipart .= «Content-Transfer-Encoding: base64rn»;
$multipart .= «rn»;
$multipart .= chunk_split(base64_encode(iconv(«utf8», «windows-1251″, $message))); // первая часть само сообщение
// Открыли файл
$fp = fopen($filepath,»r»);
if (!$fp)
{
print «Не удается открыть файл22»;
exit();
}
$file = fread($fp, filesize($filepath)); // чтение файла
fclose($fp);
$message_part = «rn—$boundaryrn»;
$message_part .= «Content-Type: application/zip; name=»$filename»rn»;
$message_part .= «Content-Disposition: attachmentrn»;
$message_part .= «Content-Transfer-Encoding: base64rn»;
$message_part .= «rn»;
$message_part .= chunk_split(base64_encode($file));
$message_part .= «rn—$boundary—rn»; // второй частью прикрепляем файл, можно прикрепить два и более файла
$multipart .= $message_part;

$result = $mailSMTP->send(‘xxx@xxx.ru’, $subject, $multipart, $headers); // отправляем письмо
// $result = $mailSMTP->send(‘Кому письмо’, ‘Тема письма’, ‘Текст письма’, ‘Заголовки письма’);
if($result === true){
echo «Письмо успешно отправлено»;
}else{
echo «Письмо не отправлено. Ошибка: » . $result;
}

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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
<?php
error_reporting(0);
/*
 *
 * Модуль конструктора почтовых форм
 *
 * Class Mmail обрабатывает входящие на него post запросы
 *
 * Все настройки устанавливаются в шаблоне обращения
 *
 *
 * ver. 2.2
 *
 *
 */
 
class PrSendMailSmtpClass {
 
    public $smtp_username;
    public $smtp_password;
    public $smtp_host;
    public $smtp_from;
    public $smtp_port;
    public $smtp_charset;
    public $mail_to;
    public $subject;
    public $message;
    public $headers;
 
    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;
    }
 
    public function setMail_to($data) {
        $this -> mail_to = $data;
        return $this;
    }
 
    public function setSubject($data) {
        $this -> subject = $data;
        return $this;
    }
 
    public function setMessage($data) {
        $this -> message = $data;
        return $this;
    }
 
    public function setHeaders($data) {
        $this -> headers .= $data;
        return $this;
 
    }
 
    public function send() {
        $mailTo = $this -> mail_to;
        $subject = $this -> subject;
        $message = $this -> message;
        $headers = $this -> 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();
            echo  $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;
 
    }
 
}
 
Class Mmail {
 
    public $responce;
 
    public function post($query) {
        if (isset($_POST[$query])) {
            return $_POST[$query];
        }
    }
 
    public function data_post() {
        if (isset($_POST)) {
            return $_POST;
        }
    }
 
    public function __construct() {
 
        $mail_configs = $_SERVER['DOCUMENT_ROOT'] . '/mail-configs.php';
 
        if (!file_exists($mail_configs)) {
            copy($_SERVER['DOCUMENT_ROOT'] . '/mailer/mail-configs.php', $mail_configs);
        }
 
        if (!isset($_SESSION)) {
            session_start();
        }
 
        header("Content-Type: text/html; charset=utf-8");
 
        $responce = null;
        $mail = null;
        $error = null;
        $response = null;
        $table_cart = null;
        $sum = null;
 
        $mail .= '<h2>' . $this -> post('subject') . '</h2>';
 
        if ($this -> post('mail')) {
            $mail .= '<table style="width: 100%; border-collapse: collapse;">';
 
            foreach ($this->data_post() as $key => $value) {
 
                if (strstr($key, '{Y}')) {
 
                    preg_match_all('#(.+?){#is', $key, $arr);
 
                    $name = $arr[1][0];
 
                    $name_ = $arr[1][0];
 
                    $name = $this -> post($name_ . '{title}{Y}');
 
                    if (!$this -> post($name_ . '{value}')) {
 
                        if ($name_) {
 
                            $response .= json_encode(array("field_is_not" => $name_ . '{title}{Y}'));
 
                            $error = true;
 
                        }
 
                    }
 
                }
 
                if (!$error) {
 
                    if (strstr($key, '{title}')) {
 
                        $mail .= '<tr><td style="padding: 5px; border: 1px solid #333;"><b>' . $this -> post($key) . '</b></td>';
 
                        preg_match_all('#(.+?){#is', $key, $arr);
 
                        $name = $arr[1][0];
 
                        $mail .= '<td style="padding: 5px; border: 1px solid #333;">' . $this -> post($name . '{value}') . '</td></tr>';
                    }
 
                }
 
            }
 
            $mail .= '  </table>';
 
            if ($this -> post('captha-ignor') != 'Y') {
 
                if ($_SESSION['captcha'] !== strtoupper($this -> post('captha_code'))) {
                    $error = true;
                    $response .= json_encode(array("captha" => "false"));
 
                }
 
            }
 
            if (!$error) {
 
                $response = json_encode(array("sent_your" => "Y"));
 
                $arConfigs =
                include $mail_configs;
 
                $mails = explode(",", $this -> post('mail'));
 
                $subject = $this -> post('subject');
 
                $headers = "MIME-Version: 1.0rn";
 
                $headers .= "From: Почтовый модуль Samedia <modMailer@samedia.ru>rn";
 
                $headers .= "Content-type: text/html; charset=iso-8859-1rn";
 
                $mail_smtp = new PrSendMailSmtpClass($arConfigs['yandex-mail'], $arConfigs['yandex-mail-sassword'], 'https://mail.clear-mir161.ru', 'pr', 465);
 
                $mail_smtp -> setHeaders("MIME-Version: 1.0rn") -> setHeaders("Content-type: text/html; charset=utf-8rn") -> setHeaders("From: Почтовый модуль Samedia <modMailer@samedia.ru>rn");
 
                $mail_smtp -> setSubject($subject) -> setMessage($mail);
 
                if ($mails) {
                    foreach ($mails as $val) {
 
                        $val = strtr($val, array(
                            "%" => "@",
                            "|" => "."
                        ));
                        $val = strtr($val, array(
                            "#" => "@",
                            "?" => "."
                        ));
                        $val = strtr($val, array(
                            ">" => "@",
                            "<" => "."
                        ));
 
                        if ($arConfigs['smtp'] == 'Y') {
 
                            $mail_smtp -> setMail_to($val) -> send();
 
                        } else {
 
                            mail($val, $subject, $mail, $headers);
                        }
 
                    }
                }
 
            }
 
            $this -> responce = $response;
        }
 
    }
 
}
 
$mailer = new Mmail;
 
if ($mailer -> responce) {
    print $mailer -> responce;
}

Страницы

  • Друзья
  • Карта сайта
  • О сайте

Промо

Задержка RCPT TO. Сервер не отвечает на RCPT TO. И почта не отправляется из-за таймаута.

На работе столкнулся с траблом. Не могли отправить письма на один почтовый сервер. Там установлен EXIM. Мы их почту получаем, а они нашу не получают.Причем зависимости не было никакой. Иногда доходит, иногда нет и с каждый днем все чаще не доходит.

Начал пробиваться телнетом к их серваку. После команды RCPT TO их сервез отвечал только через 65 секунд. У нас максимальное время ожидания было установлено по умолчанию 30.

Начали копать логи, заметили что после команды RCPT TO сервер виснет и тупит больше минуты. Часто письма просто не отправляются адресатам. Принимаем почту всю а отправить не можем.

Существует в почтовых серверах проверка на существование обратного адреса, чтобы не слали письма с несуществующих адресов. Механизм проверки выглядит так:

Сервер получает письмо от ящика отправителя, и пробует отправить 2 команды MX серверу домена, который шлет нам письмо.

MAIL FROM: <> (здесь он пустой)
220 OK
RCPT TO: <адресотправителя>
220 OK

То есть, это похоже на процедуру доставки письма, только без команды DATA и передачи тела письма. В нашем случае сервер ее не проходит.

telnet mail.domain.ru 25
Trying 165.245.11.21…
Connected to mail.domain.ru.
Escape character is ‘^]’.
220 mail.domain.ru, ESMTP
EHLO mx1.domain.ru
250- mail.domain.ru Hello 10.67.12.33 [10.67.12.33]
250-SIZE 15728640
250-PIPELINING
250-AUTH PLAIN LOGIN CRAM-MD5
250 HELP
MAIL FROM: <>
250 OK
RCPT TO: <address@domain.ru>

Команда MAIL FROM проходит нормально и ответ приходит практически сразу. И после отправки команды RCPT должен прийти ответ, но ответа нет. Сервер виснет на последней команде, ждет 30 секунд и отключается по таймату не получив ответа, поэтому письмо отклоняется.

Это очень похоже на работу антиспам системы. Это стандартная функция проверки. Дело в том, что когда спамер соединяется с вашим SMTP он таким образом может перебрать пользователей и каждый раз будет получать ответ от SMTP о наличии или отсутствии данного пользователя. Задержка ответа сильно затруднит ему работу. Просто нужно правильно настроить эту опцию. Так же в этот момент может осуществляться обратное соединение, что бы проверить отправителя.

Также стоит проверить списки RBL провайдеров, возможно какие-то из них уже не существуют. RBL провайдеры предоставляют свободный доступ к базе спамеров, чтобы с большой долей вероятности детектировать спам.

В нашем случае проблема была не из-за несуществующего IPBlockListProvider-a. При попытке проверить IP отправителя по всем базам он тупо подписал на одном из них. И почта отклонялась по таймауту.

У их EXIM был установлен слишком большой таймаут. 65 секунд. Поправили конфиг — почта пошла. В следующей статье опишу, что именно правили.

Поиск по сайту

Статистика

Мета

  • Админ
  • RSS записей
  • RSS комментариев

Функция mail() бывает блокируется на хостинге или самом сайте. Если писать в службу поддержки долго или не имеет смысла — придется отправлять письма через SMTP.

СПОСОБ 1 — просто вставляем этот код на сайте с некоторыми настройками:

<?php
$config[‘smtp_username’] = ‘support@yandeg.ru’; //Смените на имя своего почтового ящика. (ваш email)
$config[‘smtp_port’] = ’25’; // Порт работы. Не меняйте, если не уверены. На 2014 порт вроде 465. ЕСЛИ ВООБЩЕ НЕ РАБОТАЕТ — убрать кавычки в 25
$config[‘smtp_host’] = ‘smtp.yandex.ru’; //сервер для отправки почты
$config[‘smtp_password’] = ‘pass’; //Измените пароль (от вашего ящика)
$config[‘smtp_debug’] = true; //Если Вы хотите видеть сообщения ошибок, укажите true вместо false
$config[‘smtp_charset’] = ‘windows-1251’; //кодировка сообщений. (или UTF-8, итд) (меняется также в самом низу)
$config[‘smtp_from’] = ‘Leon1010’; //Ваше имя — или имя Вашего сайта. Будет показывать при прочтении в поле «От кого»
function smtpmail($mail_to, $subject, $message, $headers=») {
global $config;
$SEND = «Date: «.date(«D, d M Y H:i:s») . » UTrn»;
$SEND .= ‘Subject: =?’.$config[‘smtp_charset’].’?B?’.base64_encode($subject).»=?=rn»;
if ($headers) $SEND .= $headers.»rnrn»;
else
{
$SEND .= «Reply-To: «.$config[‘smtp_username’].»rn»;
$SEND .= «MIME-Version: 1.0rn»;
$SEND .= «Content-Type: text/plain; charset=»».$config[‘smtp_charset’].»»rn»;
$SEND .= «Content-Transfer-Encoding: 8bitrn»;
$SEND .= «From: «».$config[‘smtp_from’].»» <«.$config[‘smtp_username’].»>rn»;
$SEND .= «To: $mail_to <$mail_to>rn»;
$SEND .= «X-Priority: 3rnrn»;
}
$SEND .= $message.»rn»;
if( !$socket = fsockopen($config[‘smtp_host’], $config[‘smtp_port’], $errno, $errstr, 30) ) {
if ($config[‘smtp_debug’]) echo $errno.»<br>».$errstr;
return false;
}

if (!server_parse($socket, «220», __LINE__)) return false;

fputs($socket, «HELO » . $config[‘smtp_host’] . «rn»);
if (!server_parse($socket, «250», __LINE__)) {
if ($config[‘smtp_debug’]) echo ‘<p>Не могу отправить HELO!</p>’;
fclose($socket);
return false;
}
fputs($socket, «AUTH LOGINrn»);
if (!server_parse($socket, «334», __LINE__)) {
if ($config[‘smtp_debug’]) echo ‘<p>Не могу найти ответ на запрос авторизаци.</p>’;
fclose($socket);
return false;
}
fputs($socket, base64_encode($config[‘smtp_username’]) . «rn»);
if (!server_parse($socket, «334», __LINE__)) {
if ($config[‘smtp_debug’]) echo ‘<p>Логин авторизации не был принят сервером!</p>’;
fclose($socket);
return false;
}
fputs($socket, base64_encode($config[‘smtp_password’]) . «rn»);
if (!server_parse($socket, «235», __LINE__)) {
if ($config[‘smtp_debug’]) echo ‘<p>Пароль не был принят сервером как верный! Ошибка авторизации!</p>’;
fclose($socket);
return false;
}
fputs($socket, «MAIL FROM: <«.$config[‘smtp_username’].»>rn»);
if (!server_parse($socket, «250», __LINE__)) {
if ($config[‘smtp_debug’]) echo ‘<p>Не могу отправить комманду MAIL FROM: </p>’;
fclose($socket);
return false;
}
fputs($socket, «RCPT TO: <» . $mail_to . «>rn»);

if (!server_parse($socket, «250», __LINE__)) {
if ($config[‘smtp_debug’]) echo ‘<p>Не могу отправить комманду RCPT TO: </p>’;
fclose($socket);
return false;
}
fputs($socket, «DATArn»);

if (!server_parse($socket, «354», __LINE__)) {
if ($config[‘smtp_debug’]) echo ‘<p>Не могу отправить комманду DATA</p>’;
fclose($socket);
return false;
}
fputs($socket, $SEND.»rn.rn»);

if (!server_parse($socket, «250», __LINE__)) {
if ($config[‘smtp_debug’]) echo ‘<p>Не смог отправить тело письма. Письмо не было отправленно!</p>’;
fclose($socket);
return false;
}
fputs($socket, «QUITrn»);
fclose($socket);
return TRUE;
}

function server_parse($socket, $response, $line = __LINE__) {
global $config;
while (@substr($server_response, 3, 1) != ‘ ‘) {
if (!($server_response = fgets($socket, 256))) {
if ($config[‘smtp_debug’]) echo «<p>Проблемы с отправкой почты!</p>$response<br>$line<br>»;
return false;
}
}
if (!(substr($server_response, 0, 3) == $response)) {
if ($config[‘smtp_debug’]) echo «<p>Проблемы с отправкой почты!</p>$response<br>$line<br>»;
return false;
}
return true;
}
?>

Использовать код можно так-же как и обычную функцию mail:
<?php
$headers = ‘MIME-Version: 1.0’ . «rn»;
$headers .= ‘Content-type: text/html; charset=»windows-1251«‘ . «rn»;
$headers .= ‘From: vasya@pupkin.ru’. «rn»;
smtpmail(’email-получателя@mail.ru’, ‘Тема письма’, ‘Текст письма’, $headers);
?>

СПОСОБ 2 — просто копируем его на сайт и нечего не настраиваем

<?php
/**
* SendMailSmtpClass
*
* Класс для отправки писем через SMTP с авторизацией
*
* @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’);
}

fputs($socket, «HELO » . $this->smtp_host . «rn»);
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’);
}

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;

}
}

Вызываем теперь класс с параметрами

require_once «SendMailSmtpClass.php»; // подключаем класс

$mailSMTP = new SendMailSmtpClass(‘zhenikipatov@yandex.ru’, ‘****’, ‘smtp.yandex.ru’, ‘Evgeniy’); // создаем экземпляр класса
// $mailSMTP = new SendMailSmtpClass(‘логин’, ‘пароль’, ‘хост’, ‘имя отправителя’);

// заголовок письма
$headers= «MIME-Version: 1.0rn»;
$headers .= «Content-type: text/html; charset=utf-8rn»; // кодировка письма
$headers .= «From: Evgeniy <admin@vk-book.ru>rn»; // от кого письмо
$result = $mailSMTP->send(‘zhenikipatov@yandex.ru’, ‘Тема письма’, ‘Текст письма’, $headers); // отправляем письмо
// $result = $mailSMTP->send(‘Кому письмо’, ‘Тема письма’, ‘Текст письма’, ‘Заголовки письма’);
if($result === true){
echo «Письмо успешно отправлено»;
}else{
echo «Письмо не отправлено. Ошибка: » . $result;
}

Материал взят частично с сайтов:

http://i-leon.ru/smtp-php/

Отправка писем через SMTP с авторизацией на php

| 2014-09-01 | Отправка писем через SMTP на PHP 2 способа | Функция mail() бывает блокируется на хостинге или самом сайте. Если писать в службу поддержки долго или не имеет смысла — придется отправлять письма ч |

Email errors can be really bothersome – they can hit you hard and unexpected, when you attempt to send an urgent mail.

As part of our Server Support services for web hosting providers, we resolve email errors faced by website owners.

One commonly encountered email error is “SMTP error from remote mail server after RCPT TO”. It shows up when users try to send mails to other email accounts.

What is the error “SMTP error from remote mail server after RCPT TO”?

This error message is a very confusing one, as it can be triggered due to a number of causes. But usually the bounce message that arrives contains the details about the error.

The RCPT command is used to tell the sender mail server, who the recipient of your message is. The error message denotes that the sending mail server faced an error during that command, while trying to send mails.

To know the exact reason for the error, we examine the entire bounce message that the sender receives. And here are some of the major causes we’ve identified.

“SMTP error from remote mail server after RCPT TO” error – Causes & Fixes!

Mail server configuration issue or blacklisting, anything can cause a mail delivery error. We’ll see how to relate to the cause, from the error message we get.

1. Configuration errors

SMTP error from remote mail server after RCPT TO:<user@domain.com>:
host domain.com [xx.xx.xx.xx]: 550-Please turn on SMTP Authentication in your mail client.
550-(host.domain.com) [yy.yy.yy.yy]: __ is not permitted to relay through this server without authentication.

Cause: The authentication errors mostly occur due to mail client or mail form configuration settings. If you try to send mails without proper authentication of your mail account, the mail server throws this error.

The authentication error also occurs when there is any mail server configuration issue – like domain not present in localdomains file or MX record mismatches.

Fix: The mail client settings should be properly configured with mail account details, SMTP server and port number. For PHP mail forms, using SMTP authentication to send out mails can help resolve this error.

To resolve mail server configuration errors, we examine the mail logs, MX records and related configuration files, and fix the discrepancies that are found in them.

2. Domain blacklists

SMTP error from remote mail server after RCPT TO:<user@domain.com>:
host domain.com [xx.xx.xx.xx]: 550-"JunkMail rejected - host.domain.com [yy.yy.yy.yy]: 
___ is in an RBL, see http://www.spamhaus.org/query/bl?ip=________"
SMTP error from remote mail server after RCPT TO:: host host.domain.com [xx.xx.xx.xx]: 
554 5.7.1 Service unavailable; Client host [yy.yy.yy.yy] blocked using zen.spamhaus.org; http://www.spamhaus.org

Cause: RBLs aka blacklists are used by mail servers to prevent inbound spamming. When blacklist providers such as Spamhaus suspect your mail server as a spam origin, they will blacklist your server IP.

Getting blacklisted indicates that your server had a spammer or someone who is sending mass mails. Many times, server owners get to know about it only when users complain about mail errors.

Fix: Once blacklisted, getting de-listed is a time-consuming procedure. Pinpointing the source of spam and fixing it is the most important step. Then you need to request RBL to remove you from the list.

To ensure seamless mail delivery, it is important to avoid getting blacklisted. At Bobcares, we proactively secure the mail server and keep constant vigil on them to avoid all spamming activities that can cause the server to get blacklisted.

3. RDNS misconfiguration

SMTP error from remote mail server after RCPT TO:<user@domain.com>:
host mx.domain.com [xx.xx.xx.xx]: 554 5.7.1 <unknown[yy.yy.yy.yy]>:
Client host rejected: envelope policy RBL PTRNUL

Cause: RDNS pointer records are used to map IP to hostname and it helps to validate a server. Many mail servers reject incoming mails from servers without proper RDNS records.

Fix: Setting RDNS records for the sending mail server helps to avoid such errors. At Bobcares, we configure critical mail records such as RDNS, SPF, DKIM, etc to ensure that mail delivery errors are avoided.

4. Recipient errors

SMTP error from remote mail server after RCPT TO: <user@domain.com>:
552 5.1.1 <user@domain.com> Mailbox delivery failure policy error
SMTP error from remote mail server after RCPT TO:
550 5.1.1 xxxxxxxx Recipient Suspended (TT999)
SMTP error from remote mail server after RCPT TO:<user@domain.com>:
550 5.1.1 <user@domain.com> Recipient not found.
SMTP error from remote mail server after RCPT TO:<user@domain.com>:
host mx.domain.com [xx.xx.xx.xx]: 550 Requested action not taken: mailbox unavailable

Cause: The mail delivery error ‘SMTP error from remote mail server after RCPT TO:’, can be caused by a range of issues at the recipient mail server.

These include missing or suspended recipient email account, incorrect MX records, custom blacklists or filters configured at the recipient email account, which cause mails to bounce back to sender.

Fix: The MX records of the recipient domain should be tested and confirmed to be working fine. For resolving issues at recipient end, you need to contact the remote mail server with these inputs.

5. Sender errors

SMTP error from remote mail server after RCPT  TO:<user@domain.com>:
host host.domain.com [xx.xx.xx.xx]: 554 5.1.8  <user1@domain1.com>:
Sender address rejected: Domain not found
SMTP error from remote mail server after RCPT TO:<user2@domain2.com>:
host mx.server.com [xxx.xxx.xxx.xxx]: 550-Verification failed for <user1@domain1.com>
550-No Such User Here : Sender verify failed

Cause: A sender error can be caused due to many factors. The prominent reasons we have seen in our role as Website Support Techs for web hosting companies, include:

a. Duplicate sender account present in the recipient server
b. Misconfigured mail configuration settings
c. Sender email account doesn’t exist or cannot be detected
d. Permission issues caused by server migrations, updates or custom scripts

Fix: To resolve sender errors, we examine the mail server logs, sender email account settings, folder permissions, mail server configuration, etc. and resolve any issues related to that.

At Bobcares, our custom checklists for migrations and updates enable us to avoid any related issues that may pop up. We also audit the mail server settings periodically and reconfigure the ‘Email Routing’ as appropriate.

Conclusion

“SMTP error from remote mail server after RCPT TO” error is a common error that affects email delivery. Here we’ve discussed five major causes our Server Support Engineers have seen and how we fix it.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

SEE SERVER ADMIN PLANS

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Overview

The error indicates that the SMTP server has not accepted the recipient’s email address.

Cause

The Command RCPT failed error indicates that the SMTP server has not accepted the email recipient’s address. Some possible causes are that:

  • The email address is not in valid format.
  • The SMTP server is limiting the scope of allowed recipients.
  • Provided FROM address is not allowed.
  • Most likely, the user authentication is required.

Event examples

See some examples of the Command RCPT failed Event messages:

  • Couldn’t send message, Server Response: 550 Relaying is prohibited.
  • 550 5.7.1 Unable to relay.
  • 550 Relaying denied.
  • 554 Relay access denied.
  • 554 5.2.252 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied; Failed to process message due to a permanent exception with message Cannot submit message … [Hostname=EC9R981NB1000.USRP198.PROD.OUTLOOK.COM] 250 2.1.0

Solution

If the error returns a message similar to those above, it means that authentication with the SMTP server is required and thus has to be configured properly. Go to the Email tab of Automation Workshop Options (accessible from the Tools menu) and make sure that a Username, Password and Authentication method are correctly specified.

If unsure about SMTP server parameters or would like to use Gmail as SMTP, read more on SMTP server configuration.

Summary

Common causes of the SMTP error:

  • FROM address not allowed (you must use the same address as for authentication).
  • TO address not permitted.
  • Authentication required to send outside your organization.
  • SSL or TLS encrypted connection required to send emails.

More relaying debugging…

  • Test SMTP connection and send test email
  • AW Event 50463 · An unexpected response after end-of-mail indicator
  • AW Event 2501 · Could not send notification email
  • Command Line Email relaying access denied
  • Gmail Workspace SMTP error reference
  • Microsoft Office 365 authentication issues

Automate now!

Need assistance?

If you have any questions, please do not hesitate to contact our support team.

За последние 24 часа нас посетили 11493 программиста и 1155 роботов. Сейчас ищут 375 программистов …


  1. trusty

    С нами с:
    19 ноя 2018
    Сообщения:
    5
    Симпатии:
    0

    Парюсь третий день над кодом. Почему-то если вместо ‘текст письма’ вставляю переменную или пишу так: ‘текст письма’.$string ($string — строка, которая создается заранее и echo её отображает без проблем, выглядит строка так как нужно) — письмо не отправляется и возникает ошибка на странице:
    Письмо не отправлено. Ошибка: E-mail didn’t sent

    1. foreach($a as $myarr => $s)
    2. $body.= «{$myarr}$s<br>»;
    3. $result = $mailSMTP->send(‘kih@9876543.ru’, ‘Письмо!’, ‘<br>’.$body, $headers); // отправляем письмо

    Этот код отправляет почту, но без названий найденных файлов.

    1. header(«Content-Type: text/html; charset=windows-1251»);
    2. $string_to_search=‘ticket’;
    3. while(($file = readdir($dir)) !== false)
    4.     $a[] = strstr($file,$string_to_search);
    5. //вывод названий файлов в папке без цифр и по маске ticket в названии
    6. require_once «SendMailSmtpClass.php»; // подключаем класс
    7. $mailSMTP = new SendMailSmtpClass(‘vikt@mail.ru’, ‘hhDt6dh@78’, ‘smtp.mail.ru’, ‘vikt’); // создаем экземпляр класса
    8. // $mailSMTP = new SendMailSmtpClass(‘логин’, ‘пароль’, ‘хост’, ‘имя отправителя’);
    9. $headers= «MIME-Version: 1.0rn«;
    10. $headers .= «Content-type: text/html; charset=windows-1251rn«; // кодировка письма
    11. $headers .= «From: vikt <vikt@mail.ru>rn«; // от кого письмо
    12. $result = $mailSMTP->send(‘kih@9876543.ru’, ‘письмо!’, ‘текст письма’, $headers); // отправляем письмо
    13. echo «Письмо успешно отправлено»;
    14. echo «Письмо не отправлено. Ошибка: « . $result;

    Натолкните на что нибудь что мне поможет отправлять названия файлов (по маске ticket) на email. Вот этот вывод echo $myarr.»<br />»; хочу отправить очень. Спасибо.


  2. trusty

    С нами с:
    19 ноя 2018
    Сообщения:
    5
    Симпатии:
    0

    SendMailSmtpClass.php

    1. * Класс для отправки писем через SMTP с авторизацией
    2. * @author Ipatov Evgeniy <admin@ipatov-soft.ru>
    3. class SendMailSmtpClass {
    4. * @var string $smtp_username — логин
    5. * @var string $smtp_password — пароль
    6. * @var string $smtp_host — хост
    7. * @var string $smtp_from — от кого
    8. * @var integer $smtp_port — порт
    9. * @var string $smtp_charset — кодировка
    10. public function __construct($smtp_username, $smtp_password, $smtp_host, $smtp_from, $smtp_port = 25, $smtp_charset = «utf-8») {
    11. $this->smtp_username = $smtp_username;
    12. $this->smtp_password = $smtp_password;
    13. $this->smtp_host = $smtp_host;
    14. $this->smtp_from = $smtp_from;
    15. $this->smtp_port = $smtp_port;
    16. $this->smtp_charset = $smtp_charset;
    17. * @param string $mailTo — получатель письма
    18. * @param string $subject — тема письма
    19. * @param string $message — тело письма
    20. * @param string $headers — заголовки письма
    21. * @return bool|string В случаи отправки вернет true, иначе текст ошибки *
    22. function send($mailTo, $subject, $message, $headers) {
    23. $contentMail = «Date: « . date(«D, d M Y H:i:s») . » UTrn«;
    24. $contentMail .= ‘Subject: =?’ . $this->smtp_charset . ‘?B?’ . base64_encode($subject) . «=?=rn«;
    25. $contentMail .= $headers . «rn«;
    26. $contentMail .= $message . «rn«;
    27. if(!$socket = @fsockopen($this->smtp_host, $this->smtp_port, $errorNumber, $errorDescription, 30)){
    28. throw new Exception($errorNumber.«.».$errorDescription);
    29. if (!$this->_parseServer($socket, «220»)){
    30. throw new Exception(‘Connection error’);
    31. fputs($socket, «HELO « . $this->smtp_host . «rn«);
    32. if (!$this->_parseServer($socket, «250»)) {
    33. throw new Exception(‘Error of command sending: HELO’);
    34. fputs($socket, «AUTH LOGINrn«);
    35. if (!$this->_parseServer($socket, «334»)) {
    36. throw new Exception(‘Autorization error’);
    37. if (!$this->_parseServer($socket, «334»)) {
    38. throw new Exception(‘Autorization error’);
    39. if (!$this->_parseServer($socket, «235»)) {
    40. throw new Exception(‘Autorization error’);
    41. fputs($socket, «MAIL FROM: «.$this->smtp_username.«rn«);
    42. if (!$this->_parseServer($socket, «250»)) {
    43. throw new Exception(‘Error of command sending: MAIL FROM’);
    44. fputs($socket, «RCPT TO: « . $mailTo . «rn«);
    45. if (!$this->_parseServer($socket, «250»)) {
    46. throw new Exception(‘Error of command sending: RCPT TO’);
    47. fputs($socket, «DATArn«);
    48. if (!$this->_parseServer($socket, «354»)) {
    49. throw new Exception(‘Error of command sending: DATA’);
    50. fputs($socket, $contentMail.«rn.rn«);
    51. if (!$this->_parseServer($socket, «250»)) {
    52. throw new Exception(«E-mail didn’t sent»);
    53. fputs($socket, «QUITrn«);
    54. private function _parseServer($socket, $response) {
    55. while (@substr($responseServer, 3, 1) != ‘ ‘) {
    56. if (!($responseServer = fgets($socket, 256))) {
    57. if (!(substr($responseServer, 0, 3) == $response)) {


  3. Ganzal

    Команда форума
    Модератор

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    Настоятельно рекомендую теперь пойти и поменять пароли


  4. trusty

    С нами с:
    19 ноя 2018
    Сообщения:
    5
    Симпатии:
    0

    1. header(«Content-Type: text/html; charset=windows-1251»);
    2. require_once «SendMailSmtpClass.php»; // подключаем класс
    3. $mailSMTP = new SendMailSmtpClass(‘fwii@mail.ru’, ‘feefegeh$GD’, ‘smtp.mailserver.ru’, ‘fwii’); // создаем экземпляр класса
    4. // $mailSMTP = new SendMailSmtpClass(‘логин’, ‘пароль’, ‘хост’, ‘имя отправителя’);
    5. $headers= «MIME-Version: 1.0rn«;
    6. $headers .= «Content-type: text/html; charset=windows-1251rn«; // кодировка письма
    7. $headers .= «From: zayavkitii <fwii@mail.ru>rn«; // от кого письмо
    8. $string_to_search=‘ticket’;
    9. while(($file = readdir($dir)) !== false)
    10.     $a[] = strstr($file,$string_to_search);
    11. //вывод названий файлов с заявками без лишних цифр и файлов по маске ticket в названии
    12. $result = $mailSMTP->send(‘kih@4252433.ru’, ‘Заявка!’, ‘ ‘.$s.‘ ‘, $headers); // отправляем письмо
    13. echo «Письмо успешно отправлено»;
    14. echo «Письмо не отправлено. Ошибка: « . $result;

    письмо по прежнему не уходит, а echo $s выводит только последнюю запись из foreach($a as $myarr) почему-то (


  5. Artur_hopf

    Artur_hopf
    Активный пользователь

    С нами с:
    7 май 2018
    Сообщения:
    2.266
    Симпатии:
    405

    Свою s засунь суда вот так, только что это тебе даст? :

    Мне кажется надо как то так:

    1.    $mailSMTP->send(‘kih@4252433.ru’,‘Заявка!’,‘ ‘.$myarr.‘ ‘,$headers);


  6. trusty

    С нами с:
    19 ноя 2018
    Сообщения:
    5
    Симпатии:
    0

    1. header(«Content-Type: text/html; charset=windows-1251»);
    2. require_once «SendMailSmtpClass.php»; // подключаем класс
    3. $mailSMTP = new SendMailSmtpClass(‘asasasas@mail.ru’, ‘3456789876543345’, ‘smtp.mailserver.ru’, ‘asasasas’); // создаем экземпляр класса
    4. // $mailSMTP = new SendMailSmtpClass(‘логин’, ‘пароль’, ‘хост’, ‘имя отправителя’);
    5. $headers= «MIME-Version: 1.0rn«;
    6. $headers .= «Content-type: text/html; charset=windows-1251rn«; // кодировка письма
    7. $headers .= «From: asasasas <asasasas@mail.ru>rn«; // от кого письмо
    8. $string_to_search=‘ticket’;
    9. while(($file = readdir($dir)) !== false)
    10.     $a[] = strstr($file,$string_to_search);
    11. //вывод названий файлов с заявками без лишних цифр и файлов по маске ticket в названии
    12. //в $s теперь то что на почту должно уйти
    13. $mailSMTP->send(«kih@747526524.ru»,«Заявка!», » <br>».$s,$headers);// отправляем письмо
    14. // не отправляет ни в фореаче ни без фореача почту…
    15. //$result = $mailSMTP->send(‘kih@3564353.ru’, ‘Заявка!’, ‘ ‘.$s.’ ‘, $headers); // отправляем письмо
    16. echo «Письмо успешно отправлено»;
    17. echo «Письмо не отправлено. Ошибка: « . $result;

    теперь переменная s содержит то что надо , отображается на странице, но когда дело до отправки мыла доходит то «Письмо не отправлено. Ошибка: «:(
    библиотека smtp send’ера что-ли косячная или мой код?..
    — Добавлено —
    Artur_hopf, благодарю!:)
    — Добавлено —

    1. echo «Письмо успешно отправлено»;
    2. echo «Письмо не отправлено. Ошибка: « . $result;

    так в конце написал вместо $result === true и скрипт выдал, что отправлено письмо, но пока его в ящике нет….


  7. trusty

    С нами с:
    19 ноя 2018
    Сообщения:
    5
    Симпатии:
    0

    поменял либу для отправки. теперь использую swift-mailer 5.4.3. и понял что одинарное равно это присваивание :) и поэтому писало что отправлено, а письмо так и не ушло.

    этот код пытается отправить переменную $s

    1. require(«lib/swift_required.php»);
    2. $string_to_search=‘ticket’;
    3. $transport = Swift_SmtpTransport::newInstance(‘smtp.mailserver.ru’, 465)
    4.   ->setUsername(‘zayavki@mailserver.ru’)
    5.   ->setPassword(‘143647352646’)
    6. $mailer = Swift_Mailer::newInstance($transport);
    7. while(($file = readdir($dir)) !== false)
    8.     $a[] = strstr($file,$string_to_search);
    9. //вывод названий файлов с заявками без лишних цифр и файлов по маске ticket в названии
    10. $message = Swift_Message::newInstance(‘Subject’)
    11.   ->setFrom(array(‘zayavki@mailserver.ru’ => ‘zayavki’))
    12.   ->setTo(array(‘kih@6436.ru’ => ‘asasasas’))
    13. $result = $mailer->send($message);

    но не везет по прежнему мне (

    1. Fatal error: Uncaught exception ‘Swift_TransportException’ with message ‘Connection could not be established with host smtp.mailserver.ru [Connection refused #111]’ in /home/zayavki/public_html/lib/classes/Swift/Transport/StreamBuffer.php:269 Stack trace: #0 /home/zayavki/public_html/lib/classes/Swift/Transport/StreamBuffer.php(62): Swift_Transport_StreamBuffer->_establishSocketConnection() #1 /home/zayavki/public_html/lib/classes/Swift/Transport/AbstractSmtpTransport.php(113): Swift_Transport_StreamBuffer->initialize(Array) #2 /home/zayavki/public_html/lib/classes/Swift/Mailer.php(79): Swift_Transport_AbstractSmtpTransport->start() #3 /home/zayavki/public_html/index_2.php(68): Swift_Mailer->send(Object(Swift_Message)) #4 {main} thrown in /home/zayavki/public_html/lib/classes/Swift/Transport/StreamBuffer.php on line 269


  8. AlexProg

    AlexProg
    Активный пользователь

    С нами с:
    13 май 2014
    Сообщения:
    320
    Симпатии:
    7

    Может из-за цикла не успевает отправлять?
    Делайте по 10 писем в минуту, допустим.
    Везде же есть лимиты…

Понравилась статья? Поделить с друзьями:
  • Error of acquiring bank or network
  • Error occurs on ace components
  • Error occurs in the template of component logincomponent
  • Error occurs in the template of component appcomponent
  • Error occurs in the template of component angular