ПУСТО

среда, 24 июня 2015 г.

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

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

Код класса SendMailSmtpClass.php
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") . " UT\r\n";
        $contentMail .= 'Subject: =?' . $this->smtp_charset . '?B?'  . base64_encode($subject) . "=?=\r\n";
        $contentMail .= $headers . "\r\n";
        $contentMail .= $message . "\r\n";
         
        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_name\r\n");
            if (!$this->_parseServer($socket, "250")) {
                fclose($socket);
                throw new Exception('Error of command sending: HELO');
            }
             
            fputs($socket, "AUTH LOGIN\r\n");
            if (!$this->_parseServer($socket, "334")) {
                fclose($socket);
                throw new Exception('Autorization error');
            }
             
             
             
            fputs($socket, base64_encode($this->smtp_username) . "\r\n");
            if (!$this->_parseServer($socket, "334")) {
                fclose($socket);
                throw new Exception('Autorization error');
            }
             
            fputs($socket, base64_encode($this->smtp_password) . "\r\n");
            if (!$this->_parseServer($socket, "235")) {
                fclose($socket);
                throw new Exception('Autorization error');
            }
             
            fputs($socket, "MAIL FROM: <".$this->smtp_username.">\r\n");
            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 . ">\r\n");    
            if (!$this->_parseServer($socket, "250")) {
                fclose($socket);
                throw new Exception('Error of command sending: RCPT TO');
            }
             
            fputs($socket, "DATA\r\n");    
            if (!$this->_parseServer($socket, "354")) {
                fclose($socket);
                throw new Exception('Error of command sending: DATA');
            }
             
            fputs($socket, $contentMail."\r\n.\r\n");
            if (!$this->_parseServer($socket, "250")) {
                fclose($socket);
                throw new Exception("E-mail didn't sent");
            }
             
            fputs($socket, "QUIT\r\n");
            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;
         
    }
}

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


Код класса libmail.php
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
<?php
 
class Mail {
    /*     определение переменных идет через VAR, для обеспечения работы в php старых версий
      массивы адресов кому отправить
      @var array
     */
 
    var $sendto = array();
    /*
      @var array
     */
    var $acc = array();
    /*
      @var array
     */
    var $abcc = array();
    /*
      прикрепляемые файлы
      @var array
     */
    var $aattach = array();
    /*
      массив заголовков
      @var array
     */
    var $xheaders = array();
    /*
      приоритеты
      @var array
     */
    var $priorities = array('1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)');
    /*
      кодировка по умолчанию
      @var string
     */
    var $charset = "windows-1251";
    var $ctencoding = "8bit";
    var $receipt = 0;
    var $text_html = "text/plain"; // формат письма. по умолчанию текстовый
    var $smtp_on = false;    // отправка через smtp. по умолчанию выключена
    var $names_email = array(); // имена для email адресов, чтобы делать вид ("Антон" <te@gg.ru>)
 
    /*
      конструктор тоже по старому объявлен для совместимости со старыми версиями php
      пошел конструктор.
      входящий параметр кодировка письма
      внесено изменение
     */
 
    function Mail($charset="") {
        $this->autoCheck(true);
        $this->boundary = "--" . md5(uniqid("myboundary"));
 
 
        if ($charset != "") {
            $this->charset = strtolower($charset);
            if ($this->charset == "us-ascii")
                $this->ctencoding = "7bit";
        }
    }
 
    /*
 
      включение выключение проверки валидности email
      пример: autoCheck( true ) проверка влючена
      по умолчанию проверка включена
 
 
     */
 
    function autoCheck($bool) {
        if ($bool)
            $this->checkAddress = true;
        else
            $this->checkAddress = false;
    }
 
    /*
 
      Тема письма
      внесено изменения кодирования не латинских символов
 
     */
 
    function Subject($subject) {
 
        $this->xheaders['Subject'] = "=?" . $this->charset . "?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode(strtr($subject, "\r\n", "  ")))) . "?=";
    }
 
    /*
 
      от кого
     */
 
    function From($from) {
 
        if (!is_string($from)) {
            echo "ошибка, From должен быть строкой";
            exit;
        }
        $temp_mass = explode(';', $from); // разбиваем по разделителю для выделения имени
        if (count($temp_mass) == 2) { // если удалось разбить на два элемента
            $this->names_email['from'] = $temp_mass[0]; // имя первая часть
            $this->xheaders['From'] = $temp_mass[1]; // адрес вторая часть
        } else { // и если имя не определено
            $this->names_email['from'] = '';
            $this->xheaders['From'] = $from;
        }
    }
 
    /*
      на какой адрес отвечать
 
     */
 
    function ReplyTo($address) {
 
        if (!is_string($address))
            return false;
 
        $temp_mass = explode(';', $address); // разбиваем по разделителю для выделения имени
 
        if (count($temp_mass) == 2) { // если удалось разбить на два элемента
            $this->names_email['Reply-To'] = $temp_mass[0]; // имя первая часть
            $this->xheaders['Reply-To'] = $temp_mass[1]; // адрес вторая часть
        } else { // и если имя не определено
            $this->names_email['Reply-To'] = '';
            $this->xheaders['Reply-To'] = $address;
        }
    }
 
    /*
      Добавление заголовка для получения уведомления о прочтении. обратный адрес берется из "From" (или из "ReplyTo" если указан)
 
     */
 
    function Receipt() {
        $this->receipt = 1;
    }
 
    /*
      set the mail recipient
      @param string $to email address, accept both a single address or an array of addresses
 
     */
 
    function To($to) {
 
        // если это массив
        if (is_array($to)) {
            foreach ($to as $key => $value) { // перебираем массив и добавляем в массив для отправки через smtp
 
                $temp_mass = explode(';', $value); // разбиваем по разделителю для выделения имени
 
                if (count($temp_mass) == 2) { // если удалось разбить на два элемента
                    $this->smtpsendto[$temp_mass[1]] = $temp_mass[1]; // ключи и значения одинаковые, чтобы исключить дубли адресов
                    $this->names_email['To'][$temp_mass[1]] = $temp_mass[0]; // имя первая часть
                    $this->sendto[] = $temp_mass[1];
                } else { // и если имя не определено
                    $this->smtpsendto[$value] = $value; // ключи и значения одинаковые, чтобы исключить дубли адресов
                    $this->names_email['To'][$value] = ''; // имя первая часть
                    $this->sendto[] = $value;
                }
            }
        } else {
            $temp_mass = explode(';', $to); // разбиваем по разделителю для выделения имени
 
            if (count($temp_mass) == 2) { // если удалось разбить на два элемента
 
                $this->sendto[] = $temp_mass[1];
                $this->smtpsendto[$temp_mass[1]] = $temp_mass[1]; // ключи и значения одинаковые, чтобы исключить дубли адресов
                $this->names_email['To'][$temp_mass[1]] = $temp_mass[0]; // имя первая часть
            } else { // и если имя не определено
 
                $this->sendto[] = $to;
                $this->smtpsendto[$to] = $to; // ключи и значения одинаковые, чтобы исключить дубли адресов
 
                $this->names_email['To'][$to] = ''; // имя первая часть
            }
        }
 
        if ($this->checkAddress == true)
            $this->CheckAdresses($this->sendto);
    }
 
    /*   Cc()
     *   установка заголдовка CC ( открытая копия, все получатели будут видеть куда ушла копия )
     *   $cc : email address(es), accept both array and string
     */
 
    function Cc($cc) {
        if (is_array($cc)) {
            $this->acc = $cc;
 
            foreach ($cc as $key => $value) { // перебираем массив и добавляем в массив для отправки через smtp
                $this->smtpsendto[$value] = $value; // ключи и значения одинаковые, чтобы исключить дубли адресов
            }
        } else {
            $this->acc[] = $cc;
            $this->smtpsendto[$cc] = $cc; // ключи и значения одинаковые, чтобы исключить дубли адресов
        }
 
        if ($this->checkAddress == true)
            $this->CheckAdresses($this->acc);
    }
 
    /*   Bcc()
     *   скрытая копия. не будет помещать заголовок кому ушло письмо
     *   $bcc : email address(es), accept both array and string
     */
 
    function Bcc($bcc) {
        if (is_array($bcc)) {
            $this->abcc = $bcc;
            foreach ($bcc as $key => $value) { // перебираем массив и добавляем в массив для отправки через smtp
                $this->smtpsendto[$value] = $value; // ключи и значения одинаковые, чтобы исключить дубли адресов
            }
        } else {
            $this->abcc[] = $bcc;
            $this->smtpsendto[$bcc] = $bcc; // ключи и значения одинаковые, чтобы исключить дубли адресов
        }
 
        if ($this->checkAddress == true)
            $this->CheckAdresses($this->abcc);
    }
 
    /*   Body( text [ text_html ] )
     *   $text_html в каком формате будет письмо, в тексте или html. по умолчанию стоит текст
     */
 
    function Body($body, $text_html="") {
        $this->body = $body;
 
        if ($text_html == "html")
            $this->text_html = "text/html";
    }
 
    /*   Organization( $org )
     *   set the Organization header
     */
 
    function Organization($org) {
        if (trim($org != ""))
            $this->xheaders['Organization'] = $org;
    }
 
    /*   Priority( $priority )
     *   set the mail priority
     *   $priority : integer taken between 1 (highest) and 5 ( lowest )
     *   ex: $mail->Priority(1) ; => Highest
     */
 
    function Priority($priority) {
        if (!intval($priority))
            return false;
 
        if (!isset($this->priorities[$priority - 1]))
            return false;
 
        $this->xheaders["X-Priority"] = $this->priorities[$priority - 1];
 
        return true;
    }
 
    /*
      прикрепленные файлы
 
      @param string $filename : путь к файлу, который надо отправить
      @param string $webi_filename : реальное имя файла. если вдруг вставляется файл временный, то его имя будет хрен пойми каким..
      @param string $filetype : MIME-тип файла. по умолчанию 'application/x-unknown-content-type'
      @param string $disposition : инструкция почтовому клиенту как отображать прикрепленный файл ("inline") как часть письма или ("attachment") как прикрепленный файл
     */
 
    function Attach($filename, $webi_filename="", $filetype = "", $disposition = "inline") {
        // TODO : если типа файла не указан, ставим неизвестный тип
        if ($filetype == "")
            $filetype = "application/x-unknown-content-type";
 
        $this->aattach[] = $filename;
        $this->webi_filename[] = $webi_filename;
        $this->actype[] = $filetype;
        $this->adispo[] = $disposition;
    }
 
    /*
 
      Собираем письмо
 
 
     */
 
    function BuildMail() {
 
        $this->headers = "";
 
        // создание заголовка TO.
        // добавление имен к адресам
        foreach ($this->sendto as $key => $value) {
 
            if (strlen($this->names_email['To'][$value]))
                $temp_mass[] = "=?" . $this->charset . "?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode(strtr($this->names_email['To'][$value], "\r\n", "  ")))) . "?= <" . $value . ">";
            else
                $temp_mass[] = $value;
        }
 
        $this->xheaders['To'] = implode(", ", $temp_mass); // этот заголовок будет не нужен при отправке через mail()
 
        if (count($this->acc) > 0)
            $this->xheaders['CC'] = implode(", ", $this->acc);
 
        if (count($this->abcc) > 0)
            $this->xheaders['BCC'] = implode(", ", $this->abcc);  // этот заголовок будет не нужен при отправке через smtp
 
 
        if ($this->receipt) {
            if (isset($this->xheaders["Reply-To"]))
                $this->xheaders["Disposition-Notification-To"] = $this->xheaders["Reply-To"];
            else
                $this->xheaders["Disposition-Notification-To"] = $this->xheaders['From'];
        }
 
        if ($this->charset != "") {
            $this->xheaders["Mime-Version"] = "1.0";
            $this->xheaders["Content-Type"] = $this->text_html . "; charset=$this->charset";
            $this->xheaders["Content-Transfer-Encoding"] = $this->ctencoding;
        }
 
        $this->xheaders["X-Mailer"] = "WWW.antonlife.ucoz.ru php-mail-V 1.8";
 
        // вставаляем файлы
        if (count($this->aattach) > 0) {
            $this->_build_attachement();
        } else {
            $this->fullBody = $this->body;
        }
 
 
 
        // создание заголовков если отправка идет через smtp
        if ($this->smtp_on) {
 
            // разбиваем (FROM - от кого) на юзера и домен. домен понадобится в заголовке
            $user_domen = explode('@', $this->xheaders['From']);
 
            $this->headers = "Date: " . date("D, j M Y G:i:s") . " +0700\r\n";
            $this->headers .= "Message-ID: <" . rand() . "." . date("YmjHis") . "@" . $user_domen[1] . ">\r\n";
 
 
            reset($this->xheaders);
            while (list( $hdr, $value ) = each($this->xheaders)) {
                if ($hdr == "From" and strlen($this->names_email['from']))
                    $this->headers .= $hdr . ": =?" . $this->charset . "?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode(strtr($this->names_email['from'], "\r\n", "  ")))) . "?= <" . $value . ">\r\n";
                elseif ($hdr == "Reply-To" and strlen($this->names_email['Reply-To']))
                    $this->headers .= $hdr . ": =?" . $this->charset . "?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode(strtr($this->names_email['Reply-To'], "\r\n", "  ")))) . "?= <" . $value . ">\r\n";
                elseif ($hdr != "BCC")
                    $this->headers .= $hdr . ": " . $value . "\r\n"; // пропускаем заголовок для отправки скрытой копии
            }
        }
        // создание заголовоков, если отправка идет через mail()
        else {
            reset($this->xheaders);
            while (list( $hdr, $value ) = each($this->xheaders)) {
                if ($hdr == "From" and strlen($this->names_email['from']))
                    $this->headers .= $hdr . ": =?" . $this->charset . "?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode(strtr($this->names_email['from'], "\r\n", "  ")))) . "?= <" . $value . ">\r\n";
                elseif ($hdr == "Reply-To" and strlen($this->names_email['Reply-To']))
                    $this->headers .= $hdr . ": =?" . $this->charset . "?Q?" . str_replace("+", "_", str_replace("%", "=", urlencode(strtr($this->names_email['Reply-To'], "\r\n", "  ")))) . "?= <" . $value . ">\r\n";
                elseif ($hdr != "Subject" and $hdr != "To")
                    $this->headers .= "$hdr: $value\n"; // пропускаем заголовки кому и тему... они вставятся сами
            }
        }
    }
 
    // включение отправки через smtp используя сокеты
    // после запуска этой функции отправка через smtp включена
    // для отправки через защищенное соединение сервер нужно указывать с добавлением "ssl://" например так "ssl://smtp.gmail.com"
    function smtp_on($smtp_serv, $login, $pass, $port=25, $timeout=5) {
        $this->smtp_on = true; // включаем отправку через smtp
 
        $this->smtp_serv = $smtp_serv;
        $this->smtp_login = $login;
        $this->smtp_pass = $pass;
        $this->smtp_port = $port;
        $this->smtp_timeout = $timeout;
    }
 
    function get_data($smtp_conn) {
        $data = "";
        while ($str = fgets($smtp_conn, 515)) {
            $data .= $str;
            if (substr($str, 3, 1) == " ") {
                break;
            }
        }
        return $data;
    }
 
    /*
      отправка письма
 
     */
 
    function Send() {
        $this->BuildMail();
        $this->strTo = implode(", ", $this->sendto);
 
        // если отправка без использования smtp
        if (!$this->smtp_on) {
            $res = @mail($this->strTo, $this->xheaders['Subject'], $this->fullBody, $this->headers);
        } else { // если через smtp
 
            if (!$this->smtp_serv OR !$this->smtp_login OR !$this->smtp_pass OR !$this->smtp_port)
                return false; // если нет хотя бы одного из основных данных для коннекта, выходим с ошибкой
 
 
 
                 
// разбиваем (FROM - от кого) на юзера и домен. юзер понадобится в приветсвии с сервом
            $user_domen = explode('@', $this->xheaders['From']);
 
 
            $this->smtp_log = '';
            $smtp_conn = fsockopen($this->smtp_serv, $this->smtp_port, $errno, $errstr, $this->smtp_timeout);
            if (!$smtp_conn) {
                $this->smtp_log .= "соединение с сервером не прошло\n\n";
                fclose($smtp_conn);
                return;
            }
 
            $this->smtp_log .= $data = $this->get_data($smtp_conn) . "\n";
 
            fputs($smtp_conn, "EHLO " . $user_domen[0] . "\r\n");
            $this->smtp_log .= "Я: EHLO " . $user_domen[0] . "\n";
            $this->smtp_log .= $data = $this->get_data($smtp_conn) . "\n";
            $code = substr($data, 0, 3); // получаем код ответа
 
            if ($code != 250) {
                $this->smtp_log .= "ошибка приветсвия EHLO \n";
                fclose($smtp_conn);
                return;
            }
 
            fputs($smtp_conn, "AUTH LOGIN\r\n");
            $this->smtp_log .= "Я: AUTH LOGIN\n";
            $this->smtp_log .= $data = $this->get_data($smtp_conn) . "\n";
            $code = substr($data, 0, 3);
 
            if ($code != 334) {
                $this->smtp_log .= "сервер не разрешил начать авторизацию \n";
                fclose($smtp_conn);
                return;
            }
 
            fputs($smtp_conn, base64_encode($this->smtp_login) . "\r\n");
            $this->smtp_log .= "Я: " . base64_encode($this->smtp_login) . "\n";
            $this->smtp_log .= $data = $this->get_data($smtp_conn) . "\n";
 
            $code = substr($data, 0, 3);
            if ($code != 334) {
                $this->smtp_log .= "ошибка доступа к такому юзеру\n";
                fclose($smtp_conn);
                return;
            }
 
 
            fputs($smtp_conn, base64_encode($this->smtp_pass) . "\r\n");
            $this->smtp_log .="Я: " . base64_encode($this->smtp_pass) . "\n";
            $this->smtp_log .= $data = $this->get_data($smtp_conn) . "\n";
 
            $code = substr($data, 0, 3);
            if ($code != 235) {
                $this->smtp_log .= "не правильный пароль\n";
                fclose($smtp_conn);
                return;
            }
 
            fputs($smtp_conn, "MAIL FROM:<" . $this->xheaders['From'] . "> SIZE=" . strlen($this->headers . "\r\n" . $this->fullBody) . "\r\n");
            $this->smtp_log .= "Я: MAIL FROM:<" . $this->xheaders['From'] . "> SIZE=" . strlen($this->headers . "\r\n" . $this->fullBody) . "\n";
            $this->smtp_log .= $data = $this->get_data($smtp_conn) . "\n";
 
            $code = substr($data, 0, 3);
            if ($code != 250) {
                $this->smtp_log .= "сервер отказал в команде MAIL FROM\n";
                fclose($smtp_conn);
                return;
            }
 
 
 
            foreach ($this->smtpsendto as $keywebi => $valuewebi) {
                fputs($smtp_conn, "RCPT TO:<" . $valuewebi . ">\r\n");
                $this->smtp_log .= "Я: RCPT TO:<" . $valuewebi . ">\n";
                $this->smtp_log .= $data = $this->get_data($smtp_conn) . "\n";
                $code = substr($data, 0, 3);
                if ($code != 250 AND $code != 251) {
                    $this->smtp_log .= "Сервер не принял команду RCPT TO\n";
                    fclose($smtp_conn);
                    return;
                }
            }
 
 
 
 
            fputs($smtp_conn, "DATA\r\n");
            $this->smtp_log .="Я: DATA\n";
            $this->smtp_log .= $data = $this->get_data($smtp_conn) . "\n";
 
            $code = substr($data, 0, 3);
            if ($code != 354) {
                $this->smtp_log .= "сервер не принял DATA\n";
                fclose($smtp_conn);
                return;
            }
 
            fputs($smtp_conn, $this->headers . "\r\n" . $this->fullBody . "\r\n.\r\n");
            $this->smtp_log .= "Я: " . $this->headers . "\r\n" . $this->fullBody . "\r\n.\r\n";
 
            $this->smtp_log .= $data = $this->get_data($smtp_conn) . "\n";
 
            $code = substr($data, 0, 3);
            if ($code != 250) {
                $this->smtp_log .= "ошибка отправки письма\n";
                fclose($smtp_conn);
                return;
            }
 
            fputs($smtp_conn, "QUIT\r\n");
            $this->smtp_log .="QUIT\r\n";
            $this->smtp_log .= $data = $this->get_data($smtp_conn) . "\n";
            fclose($smtp_conn);
        }
    }
 
    /*
     *   показывает что было отправлено
     *
     */
 
    function Get() {
        if (isset($this->smtp_log)) {
            if ($this->smtp_log) {
                return $this->smtp_log; // если есть лог отправки smtp выведем его
            }
        }
 
        $this->BuildMail();
        $mail = $this->headers . "\n\n";
        $mail .= $this->fullBody;
        return $mail;
    }
 
    /*
      проверка мыла
      возвращает true или false
     */
 
    function ValidEmail($address) {
 
        // если существует современная функция фильтрации данных, то проверять будем этой функцией. появилась в php 5.2
        if (function_exists('filter_list')) {
            $valid_email = filter_var($address, FILTER_VALIDATE_EMAIL);
            if ($valid_email !== false)
                return true;
            else
                return false;
        }
        else { // а если php еще старой версии, то проверка валидности пойдет старым способом
            if (ereg(".*<(.+)>", $address, $regs)) {
                $address = $regs[1];
            }
            if (ereg("^[^@  ]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2}|net|com|gov|mil|org|edu|int)\$", $address))
                return true;
            else
                return false;
        }
    }
 
    /*
 
      проверка массива адресов
 
 
     */
 
    function CheckAdresses($aad) {
        for ($i = 0; $i < count($aad); $i++) {
            if (!$this->ValidEmail($aad[$i])) {
                echo "ошибка : не верный email " . $aad[$i];
                exit;
            }
        }
    }
 
    /*
      сборка файлов для отправки
     */
 
    function _build_attachement() {
 
        $this->xheaders["Content-Type"] = "multipart/mixed;\n boundary=\"$this->boundary\"";
 
        $this->fullBody = "This is a multi-part message in MIME format.\n--$this->boundary\n";
        $this->fullBody .= "Content-Type: " . $this->text_html . "; charset=$this->charset\nContent-Transfer-Encoding: $this->ctencoding\n\n" . $this->body . "\n";
 
        $sep = chr(13) . chr(10);
 
        $ata = array();
        $k = 0;
 
        // перебираем файлы
        for ($i = 0; $i < count($this->aattach); $i++) {
 
            $filename = $this->aattach[$i];
 
            $webi_filename = $this->webi_filename[$i]; // имя файла, которое может приходить в класс, и имеет другое имя файла
            if (strlen($webi_filename))
                $basename = basename($webi_filename); // если есть другое имя файла, то оно будет таким
            else
                $basename = basename($filename); // а если нет другого имени файла, то имя будет выдернуто из самого загружаемого файла
 
            $ctype = $this->actype[$i]; // content-type
            $disposition = $this->adispo[$i];
 
            if (!file_exists($filename)) {
                echo "ошибка прикрепления файла : файл $filename не существует";
                exit;
            }
            $subhdr = "--$this->boundary\nContent-type: $ctype;\n name=\"$basename\"\nContent-Transfer-Encoding: base64\nContent-Disposition: $disposition;\n  filename=\"$basename\"\n";
            $ata[$k++] = $subhdr;
            // non encoded line length
            $linesz = filesize($filename) + 1;
            $fp = fopen($filename, 'r');
            $ata[$k++] = chunk_split(base64_encode(fread($fp, $linesz)));
            fclose($fp);
        }
        $this->fullBody .= implode($sep, $ata);
    }
 
}
 
// class Mail
?>

Пример использования:
1
2
3
4
5
6
7
8
9
10
11
<?php
    include "libmail.php"; // вставляем файл с классом
    $m= new Mail; // начинаем
    $m->From( "Василий Пупкин;мой_аккаунт@gmail.com" ); // от кого отправляется почта
    $m->To( "_мой_аккаунт_@gmail.com" ); // кому адресованно
    $m->Subject( "Тест скрипта" );
    $m->Body( "Ваш заказ принят" );  
    $m->Priority(3) ;    // приоритет письма
    $m->smtp_on("ssl://smtp.gmail.com","Логин","Пароль", 465);
    $m->Send();    // а теперь пошла отправка
?>

Комментариев нет:

Отправить комментарий