-
Notifications
You must be signed in to change notification settings - Fork 12
/
smtp.php
811 lines (724 loc) · 21.2 KB
/
smtp.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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
<?php
/**
* SMTP
*
* LICENSE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package SMTP
* @author Sergio Vaccaro <[email protected]>
* @copyright Copyright (c) Sergio Vaccaro
* @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
* @version 1.1
*/
/**
* Rich SMTP client
*
* @package SMTP
* @link http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol Documentation
*/
class smtp
{
/**
* New line character
*
* SMTP wants <CR><LF>
*/
const NL = "\r\n";
/**
* Ready status code
* @link http://www.greenend.org.uk/rjk/tech/smtpreplies.html
*/
const READY = '220';
/**
* Ok status code
* @link http://www.greenend.org.uk/rjk/tech/smtpreplies.html
*/
const OK = '250';
/**
* Text encoded as base64
* @link http://www.fehcom.de/qmail/smtpauth.html
*/
const TEXT64 = '334';
/**
* Auth OK
* @link http://www.fehcom.de/qmail/smtpauth.html
*/
const AUTHOK = '235';
/**
* Data ok
* @link @link http://www.fehcom.de/qmail/smtpauth.html
*/
const DATAOK = '354';
/**
* Bye
* @link @link http://www.fehcom.de/qmail/smtpauth.html
*/
const BYE = '221';
/**
* Mailer
*/
const MAILER = 'PHP smtp class';
/**
* Mailer author
*/
const MAILER_AUTHOR = '"Sergio Vaccaro" <[email protected]> https://github.com/hujuice/smtp';
/**
* SMTP socket resource
*
* @var resource
*/
protected $_smtp = null;
/**
* Server
*
* @var array
*/
protected $_server = array(
'host' => null,
'port' => 25,
'timeout' => 3,
);
/**
* Auth user (base64 encoded)
*
* @var string
*/
protected $_user;
/**
* Auth pass (base64 encoded)
*
* @var string
*/
protected $_pass;
/**
* Charset (excluding text and attachments)
*
* @var string
*/
protected $_charset = 'UTF-8';
/**
* From
*
* @var array
*/
protected $_from;
/**
* MAIL FROM
*
* @var string
*/
protected $_mailFrom = null;
/**
* Reply-to
*
* @var array
*/
protected $_replyTo = array();
/**
* To
*
* Multiple recipients allowed
*
* @var array
*/
protected $_to = array();
/**
* Cc
*
* Multiple recipients allowed
*
* @var array
*/
protected $_cc = array();
/**
* Bcc
*
* Multiple recipients allowed
*
* @var array
*/
protected $_bcc = array();
/**
* Priority
*
* Priorities are from 1 (low) to 5 (high)
* 3 is normal
*
* @var integer
*/
protected $_priority;
/**
* Custom headers
*
* @var array
*/
protected $_headers = array();
/**
* Subject
*
* @var string
*/
protected $_subject;
/**
* Text message
*
* @var string
*/
protected $_text = array(
'body' => '',
'Content-Type' => 'text/plain',
'charset' => 'UTF-8'
);
/**
* File attachments
*
* @var array
*/
protected $_attachments = array();
/**
* Raw attachments
*
* @var array
*/
protected $_raw = array();
/**
* Log
*
* @var string
*/
protected $_log = '';
/**
* Charset encoding
*
* @see http://www.pcvr.nl/tcpip/smtp_sim.htm
* @param string $string
*/
protected function _encode($string)
{
if ($this->_charset) {
return '=?' . $this->_charset . '?B?' . base64_encode($string) . '?=';
} else {
return $string;
}
}
/**
* Add or replace recipients
*
* @param string $dest
* @param string $destName
* @param array $class
* @throw Exception
*/
protected function _recipients($dest, $destName, $class)
{
if (in_array($class, array('_to', '_cc', '_bcc')))
{
if ($destName)
{
if ($dest)
$this->{$class}[$destName] = $dest;
else
{
if (isset($this->{$class}[$destName]))
unset($this->{$class}[$destName]);
}
}
else
{
if ($dest)
$this->{$class}[] = $dest;
}
}
else
throw new Exception('Wrong recipient');
}
/**
* Perform a request/response exchange
*
* @param string $request
* @param string $expect The expected status code
* @return string
* @throw Exception
*/
protected function _dialog($request, $expect)
{
$this->_log .= $request . PHP_EOL;
fwrite ($this->_smtp, $request . self::NL);
$response = fgets($this->_smtp);
$this->_log .= $response . PHP_EOL;
if (substr($response, 0, 3) != $expect)
throw new Exception('Message "' . $request . '" NOT accepted! Here is the dialog dump:' . PHP_EOL . $this->_log);
return $response;
}
/**
* Connection to the SMTP server
* @throw Exception
*/
public function _connect()
{
// Connect (if not already connected)
if (empty($this->_smtp))
{
if ($this->_smtp = fsockopen($this->_server['host'], $this->_server['port'], $errno, $errstr, $this->_server['timeout']))
{
if (substr($response = fgets($this->_smtp), 0, 3) != self::READY)
throw new Exception('Server NOT ready! The server responded with this message:' . PHP_EOL . $response);
$this->_log = $response . PHP_EOL;
// HELO
$sender = explode('@', $this->_from['address']);
$this->_dialog('HELO ' . $sender[1], self::OK);
// Auth
if ($this->_user && $this->_pass)
{
// See http://www.fehcom.de/qmail/smtpauth.html
$this->_dialog('auth login', self::TEXT64);
$this->_dialog($this->_user, self::TEXT64);
$this->_dialog($this->_pass, self::AUTHOK);
}
}
else
{
$message = 'Unable to connect to ' . $this->_server['host'] . ' on port ' . $this->_server['port'] . ' within ' . $this->_server['timeout'] . ' seconds' . PHP_EOL;
if (!empty($errstr))
$message .= 'The remote server responded:' . PHP_EOL . $errstr . '(' . $errno . ')';
throw new Exception($message);
}
}
}
/**
* Connection to the SMTP server
*
* @param string $host
* @param integer $port
* @param integer $timeout
* @throw Exception
*/
public function __construct($host, $port = 25 , $timeout = 3)
{
// Avoid a warning
if (empty($host))
throw new Exception('Undefined SMTP server');
// Settings
$this->_server['host'] = (string) $host;
if ($port)
$this->_server['port'] = (integer) $port;
if ($timeout)
$this->_server['timeout'] = (integer) $timeout;
}
/**
* Closes connection
*/
public function __destruct()
{
// Quit
$this->_dialog('QUIT', self::BYE);
if ($this->_smtp)
fclose($this->_smtp);
}
/**
* Auth
*
* Auth login implementation.
* Consider that there are many auth types.
*
* @param string $user
* @param string $pass
*/
public function auth($user, $pass)
{
$this->_user = base64_encode($user);
$this->_pass = base64_encode($pass);
}
/**
* Charset (excluding text and attachments)
* Note that this is the charset for Subject, names, etc.
* In a web context, should match the 'Content-Type'.
* If empty will be pure ASCII (7-bit)
*
* @param string
*/
public function charset($charset)
{
$this->_charset = (string) $charset;
}
/**
* From
*
* @param string $from
* @param string $name
* @return array
*/
public function from($from = null, $name = '')
{
if (null !== $from)
{
$this->_from['address'] = (string) $from;
$this->_from['name'] = (string) $name;
}
return $this->_from;
}
/**
* MAIL FROM
*
* @param string $mail_from
* @return string
*/
public function mailFrom($mail_from = null)
{
if (null !== $mail_from)
$this->_mailFrom = (string) $mail_from;
return $this->_mailFrom;
}
/**
* Reply-to
*
* @param string $reply_to
* @param string $name
* @return array
*/
public function replyTo($reply_to = null, $name = null)
{
if (null !== $reply_to)
{
$this->_replyTo['address'] = (string) $reply_to;
$this->_replyTo['name'] = (string) $name;
}
return $this->_replyTo;
}
/**
* To
*
* @param string $to
* @param string $toName
* @return array
*/
public function to($to = null, $toName = '')
{
$this->_recipients($to, $toName, '_to');
return $this->_to;
}
/**
* Cc
*
* @param string $cc
* @param string $ccName
* @return array
*/
public function cc($cc = null, $ccName = '')
{
$this->_recipients($cc, $ccName, '_cc');
return $this->_cc;
}
/**
* Bcc
*
* @param string $bcc
* @param string $bccName
* @return array
*/
public function bcc($bcc = null, $bccName = '')
{
$this->_recipients($bcc, $bccName, '_bcc');
return $this->_bcc;
}
/**
* Priority
*
* @param integer $priority
* @return integer
*/
public function priority($priority = null)
{
if ($priority)
{
$priority = (integer) $priority;
if (($priority > 0) && ($priority < 6))
$this->_priority = $priority;
else
throw new Exception('Priority are integer from 1 (low) to 5 (high)');
}
return $this->_priority;
}
/**
* Custom header
*
* @param string $header
* @return array
*/
public function header($name = null, $value = null)
{
if ($name)
$this->_headers[(string) $name] = (string) $value;
return $this->_headers;
}
/**
* Subject
*
* @param string $subject
* @return string
*/
public function subject($subject = null)
{
if (null !== $subject)
$this->_subject = (string) $subject;
return $this->_subject;
}
/**
* Text
*
* @param string $text
* @return string
*/
public function text($text = null, $content_type = 'text/plain', $charset = 'utf-8')
{
if (null !== $text)
{
$this->_text = array(
'body' => str_replace("\n", self::NL, (string) $text),
'Content-Type' => $content_type,
'charset' => $charset
);
}
return $this->_text;
}
/**
* Attachment from file
*
* @link http://en.wikipedia.org/wiki/MIME#Content-Transfer-Encoding
* @link http://en.wikipedia.org/wiki/MIME#Multipart_messages
* @link http://support.mozilla.org/it/questions/746116
* @param string $path
* @param string $content_type
* @param string $charset Will be used for text/* only
* @return array
*/
public function attachment($path = null, $name = '', $content_type = 'application/octet-stream', $charset = 'utf-8')
{
if (is_readable($path))
{
$attachment = array(
'path' => (string) $path,
'Content-Type' => (string) $content_type,
'charset' => (string) $charset
);
$name || ($name = pathinfo($path, PATHINFO_BASENAME));
$this->_attachments[$name] = $attachment;
}
elseif(!empty($path))
throw new Exception('File ' . $path . ' not found or not readable');
return $this->_attachments;
}
/**
* Raw attachment
*
* @link http://en.wikipedia.org/wiki/MIME#Content-Transfer-Encoding
* @link http://en.wikipedia.org/wiki/MIME#Multipart_messages
* @link http://support.mozilla.org/it/questions/746116
* @param string $name
* @param string $content
* @param string $content_type
* @param string $charset Will be used for text/* only
* @return array
*/
public function raw($content = null, $name = '', $content_type = 'text/plain', $charset = 'utf-8')
{
if ($content)
{
$attachment = array(
'content' => (string) $content,
'Content-Type' => (string) $content_type,
'charset' => (string) $charset
);
if (empty($name))
$name = time() . '-' . mt_rand();
$this->_raw[$name] = $attachment;
}
return $this->_raw;
}
/**
* Completely clear recipients, attachments and headers (for a new message)
*/
public function clear()
{
$this->_to = array();
$this->_cc = array();
$this->_bcc = array();
$this->_headers = array();
$this->_attachments = array();
$this->_raw = array();
}
/**
* Send
*
* @see http://www.pcvr.nl/tcpip/smtp_sim.htm
* @return string
* @throw Exception
*/
public function send()
{
// Check for minimum requirements
if (empty($this->_from))
throw new Exception('Sender undefined');
if (empty($this->_to) && empty($this->_cc) && empty($this->_bcc))
throw new Exception('No recipients');
if (empty($this->_subject)) // Net Ecology
throw new Exception('No subject');
if (empty($this->_text))
throw new Exception('No message text');
// Connection
$this->_connect();
// From
if ($this->_mailFrom)
$from = $this->_mailFrom;
else
$from = $this->_from['address'];
$this->_dialog('MAIL FROM:<' . $from . '>', self::OK);
// Recipients
foreach($this->_to as $rcpt)
$this->_dialog('RCPT TO:<' . $rcpt . '>', self::OK);
foreach($this->_cc as $rcpt)
$this->_dialog('RCPT TO:<' . $rcpt . '>', self::OK);
foreach($this->_bcc as $rcpt)
$this->_dialog('RCPT TO:<' . $rcpt . '>', self::OK);
// Data
$this->_dialog('DATA', self::DATAOK);
// Message
$message = '';
// From
if (empty($this->_from['name']))
$message .= 'From: <' . $this->_from['address'] . '>' . self::NL;
else
$message .= 'From: "' . $this->_encode($this->_from['name']) . '"<' . $this->_from['address'] . '>' . self::NL;
// Reply to
if (!empty($this->_replyTo))
{
if (empty($this->_replyTo['name']))
$message .= 'Reply-To: <' . $this->_replyTo['address'] . '>' . self::NL;
else
$message .= 'Reply-To: "' . $this->_encode($this->_replyTo['name']) . '"<' . $this->_replyTo['address'] . '>' . self::NL;
}
// To
foreach ($this->_to as $name => $rcpt)
{
if (is_integer($name))
$message .= 'To: <' . $rcpt . '>' . self::NL;
else
$message .= 'To: "' . $this->_encode($name) . '"<' . $rcpt . '>' . self::NL;
}
// Cc
foreach ($this->_cc as $name => $rcpt)
{
if (is_integer($name))
$message .= 'Cc: <' . $rcpt . '>' . self::NL;
else
$message .= 'Cc: "' . $this->_encode($name) . '"<' . $rcpt . '>' . self::NL;
}
// Bcc
foreach ($this->_bcc as $name => $rcpt)
{
if (is_integer($name))
$message .= 'Bcc: <' . $rcpt . '>' . self::NL;
else
$message .= 'Bcc: "' . $this->_encode($name) . '"<' . $rcpt . '>' . self::NL;
}
// Priority
if ($this->_priority)
$message .= 'X-Priority: ' . $this->_priority . self::NL;
// Mailer
$message .= 'X-mailer: ' . self::MAILER . self::NL;
$message .= 'X-mailer-author: ' . self::MAILER_AUTHOR . self::NL;
// Custom headers
foreach ($this->_headers as $name => $value)
$message .= $name . ': ' . $value. self::NL;
// Date
$message .= 'Date: ' . date('r') . self::NL;
// Subject
$message .= 'Subject: ' . $this->_encode($this->_subject) . self::NL;
// Message
/*
The message will containt text and attachments.
This implementation consider the multipart/mixed method only.
http://en.wikipedia.org/wiki/MIME#Multipart_messages
*/
if ($this->_attachments || $this->_raw)
{
$separator = hash('sha256', time());
$message .= 'MIME-Version: 1.0' . self::NL;
$message .= 'Content-Type: multipart/mixed; boundary=' . $separator . self::NL;
$message .= self::NL;
$message .= 'This is a message with multiple parts in MIME format.' . self::NL;
$message .= '--' . $separator . self::NL;
$message .= 'Content-Type: ' . $this->_text['Content-Type'] . '; charset=' . $this->_text['charset'] . self::NL;
$message .= self::NL;
$message .= $this->_text['body'] . self::NL;
foreach ($this->_attachments as $name => $attach)
{
$message .= '--' . $separator . self::NL;
$message .= 'Content-Disposition: attachment; filename=' . $name . '; modification-date="' . date('r', filemtime($attach['path'])) . '"' . self::NL;
if (substr($attach['Content-Type'], 0, 5) == 'text/')
{
$message .= 'Content-Type: ' . $attach['Content-Type'] . '; charset=' . $attach['charset'] . self::NL;
$message .= self::NL;
$message .= file_get_contents($attach['path']) . self::NL;
}
else
{
$message .= 'Content-Type: ' . $attach['Content-Type'] . self::NL;
$message .= 'Content-Transfer-Encoding: base64' . self::NL;
$message .= self::NL;
$message .= base64_encode(file_get_contents($attach['path'])) . self::NL;
}
}
foreach ($this->_raw as $name => $raw)
{
$message .= '--' . $separator . self::NL;
$message .= 'Content-Disposition: attachment; filename=' . $name . '; modification-date="' . date('r') . '"' . self::NL;
if (substr($raw['Content-Type'], 0, 5) == 'text/')
{
$message .= 'Content-Type: ' . $raw['Content-Type'] . '; charset=' . $raw['charset'] . self::NL;
$message .= self::NL;
$message .= $raw['content'] . self::NL;
}
else
{
$message .= 'Content-Type: ' . $raw['Content-Type'] . self::NL;
$message .= 'Content-Transfer-Encoding: base64' . self::NL;
$message .= self::NL;
$message .= base64_encode($raw['content']) . self::NL;
}
}
$message .= '--' . $separator . '--' . self::NL;
}
else
{
$message .= 'Content-Type: ' . $this->_text['Content-Type'] . '; charset=' . $this->_text['charset'] . self::NL;
$message .= self::NL . $this->_text['body'] . self::NL;
}
$message .= '.'; // The _dialog function below will add self::NL;
// Body!
$send = $this->_dialog($message, self::OK);
return substr($send, 4);
}
/**
* Dump the log
*
* @return string
*/
public function dump()
{
return $this->_log;
}
}