Subversion Repositories cheapmusic

Rev

Rev 25 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
25 - 1
<?php
2
/**
3
 * PHPMailer RFC821 SMTP email transport class.
4
 * PHP Version 5.5.
5
 *
6
 * @see       https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
7
 *
8
 * @author    Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
9
 * @author    Jim Jagielski (jimjag) <jimjag@gmail.com>
10
 * @author    Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
11
 * @author    Brent R. Matzelle (original founder)
12
 * @copyright 2012 - 2017 Marcus Bointon
13
 * @copyright 2010 - 2012 Jim Jagielski
14
 * @copyright 2004 - 2009 Andy Prevost
15
 * @license   http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
16
 * @note      This program is distributed in the hope that it will be useful - WITHOUT
17
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18
 * FITNESS FOR A PARTICULAR PURPOSE.
19
 */
20
 
21
namespace PHPMailer\PHPMailer;
22
 
23
/**
24
 * PHPMailer RFC821 SMTP email transport class.
25
 * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.
26
 *
27
 * @author  Chris Ryan
28
 * @author  Marcus Bointon <phpmailer@synchromedia.co.uk>
29
 */
30
class SMTP
31
{
32
    /**
33
     * The PHPMailer SMTP version number.
34
     *
35
     * @var string
36
     */
73 - 37
    const VERSION = '6.0.7';
25 - 38
 
39
    /**
40
     * SMTP line break constant.
41
     *
42
     * @var string
43
     */
44
    const LE = "\r\n";
45
 
46
    /**
47
     * The SMTP port to use if one is not specified.
48
     *
49
     * @var int
50
     */
51
    const DEFAULT_PORT = 25;
52
 
53
    /**
54
     * The maximum line length allowed by RFC 2822 section 2.1.1.
55
     *
56
     * @var int
57
     */
58
    const MAX_LINE_LENGTH = 998;
59
 
60
    /**
61
     * Debug level for no output.
62
     */
63
    const DEBUG_OFF = 0;
64
 
65
    /**
66
     * Debug level to show client -> server messages.
67
     */
68
    const DEBUG_CLIENT = 1;
69
 
70
    /**
71
     * Debug level to show client -> server and server -> client messages.
72
     */
73
    const DEBUG_SERVER = 2;
74
 
75
    /**
76
     * Debug level to show connection status, client -> server and server -> client messages.
77
     */
78
    const DEBUG_CONNECTION = 3;
79
 
80
    /**
81
     * Debug level to show all messages.
82
     */
83
    const DEBUG_LOWLEVEL = 4;
84
 
85
    /**
86
     * Debug output level.
87
     * Options:
88
     * * self::DEBUG_OFF (`0`) No debug output, default
89
     * * self::DEBUG_CLIENT (`1`) Client commands
90
     * * self::DEBUG_SERVER (`2`) Client commands and server responses
91
     * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status
92
     * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages.
93
     *
94
     * @var int
95
     */
96
    public $do_debug = self::DEBUG_OFF;
97
 
98
    /**
99
     * How to handle debug output.
100
     * Options:
101
     * * `echo` Output plain-text as-is, appropriate for CLI
102
     * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
103
     * * `error_log` Output to error log as configured in php.ini
104
     * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
105
     *
106
     * ```php
107
     * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
108
     * ```
109
     *
110
     * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`
111
     * level output is used:
112
     *
113
     * ```php
114
     * $mail->Debugoutput = new myPsr3Logger;
115
     * ```
116
     *
117
     * @var string|callable|\Psr\Log\LoggerInterface
118
     */
119
    public $Debugoutput = 'echo';
120
 
121
    /**
122
     * Whether to use VERP.
123
     *
124
     * @see http://en.wikipedia.org/wiki/Variable_envelope_return_path
125
     * @see http://www.postfix.org/VERP_README.html Info on VERP
126
     *
127
     * @var bool
128
     */
129
    public $do_verp = false;
130
 
131
    /**
132
     * The timeout value for connection, in seconds.
133
     * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
134
     * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.
135
     *
136
     * @see http://tools.ietf.org/html/rfc2821#section-4.5.3.2
137
     *
138
     * @var int
139
     */
140
    public $Timeout = 300;
141
 
142
    /**
143
     * How long to wait for commands to complete, in seconds.
144
     * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
145
     *
146
     * @var int
147
     */
148
    public $Timelimit = 300;
149
 
150
    /**
151
     * Patterns to extract an SMTP transaction id from reply to a DATA command.
152
     * The first capture group in each regex will be used as the ID.
153
     * MS ESMTP returns the message ID, which may not be correct for internal tracking.
154
     *
155
     * @var string[]
156
     */
157
    protected $smtp_transaction_id_patterns = [
158
        'exim' => '/[\d]{3} OK id=(.*)/',
159
        'sendmail' => '/[\d]{3} 2.0.0 (.*) Message/',
160
        'postfix' => '/[\d]{3} 2.0.0 Ok: queued as (.*)/',
161
        'Microsoft_ESMTP' => '/[0-9]{3} 2.[\d].0 (.*)@(?:.*) Queued mail for delivery/',
162
        'Amazon_SES' => '/[\d]{3} Ok (.*)/',
163
        'SendGrid' => '/[\d]{3} Ok: queued as (.*)/',
164
        'CampaignMonitor' => '/[\d]{3} 2.0.0 OK:([a-zA-Z\d]{48})/',
165
    ];
166
 
167
    /**
168
     * The last transaction ID issued in response to a DATA command,
169
     * if one was detected.
170
     *
171
     * @var string|bool|null
172
     */
173
    protected $last_smtp_transaction_id;
174
 
175
    /**
176
     * The socket for the server connection.
177
     *
178
     * @var ?resource
179
     */
180
    protected $smtp_conn;
181
 
182
    /**
183
     * Error information, if any, for the last SMTP command.
184
     *
185
     * @var array
186
     */
187
    protected $error = [
188
        'error' => '',
189
        'detail' => '',
190
        'smtp_code' => '',
191
        'smtp_code_ex' => '',
192
    ];
193
 
194
    /**
195
     * The reply the server sent to us for HELO.
196
     * If null, no HELO string has yet been received.
197
     *
198
     * @var string|null
199
     */
200
    protected $helo_rply = null;
201
 
202
    /**
203
     * The set of SMTP extensions sent in reply to EHLO command.
204
     * Indexes of the array are extension names.
205
     * Value at index 'HELO' or 'EHLO' (according to command that was sent)
206
     * represents the server name. In case of HELO it is the only element of the array.
207
     * Other values can be boolean TRUE or an array containing extension options.
208
     * If null, no HELO/EHLO string has yet been received.
209
     *
210
     * @var array|null
211
     */
212
    protected $server_caps = null;
213
 
214
    /**
215
     * The most recent reply received from the server.
216
     *
217
     * @var string
218
     */
219
    protected $last_reply = '';
220
 
221
    /**
222
     * Output debugging info via a user-selected method.
223
     *
224
     * @param string $str   Debug string to output
225
     * @param int    $level The debug level of this message; see DEBUG_* constants
226
     *
227
     * @see SMTP::$Debugoutput
228
     * @see SMTP::$do_debug
229
     */
230
    protected function edebug($str, $level = 0)
231
    {
232
        if ($level > $this->do_debug) {
233
            return;
234
        }
235
        //Is this a PSR-3 logger?
236
        if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) {
237
            $this->Debugoutput->debug($str);
238
 
239
            return;
240
        }
241
        //Avoid clash with built-in function names
242
        if (!in_array($this->Debugoutput, ['error_log', 'html', 'echo']) and is_callable($this->Debugoutput)) {
243
            call_user_func($this->Debugoutput, $str, $level);
244
 
245
            return;
246
        }
247
        switch ($this->Debugoutput) {
248
            case 'error_log':
249
                //Don't output, just log
250
                error_log($str);
251
                break;
252
            case 'html':
253
                //Cleans up output a bit for a better looking, HTML-safe output
254
                echo gmdate('Y-m-d H:i:s'), ' ', htmlentities(
255
                    preg_replace('/[\r\n]+/', '', $str),
256
                    ENT_QUOTES,
257
                    'UTF-8'
258
                ), "<br>\n";
259
                break;
260
            case 'echo':
261
            default:
262
                //Normalize line breaks
263
                $str = preg_replace('/\r\n|\r/ms', "\n", $str);
264
                echo gmdate('Y-m-d H:i:s'),
265
                "\t",
266
                    //Trim trailing space
267
                trim(
268
                //Indent for readability, except for trailing break
269
                    str_replace(
270
                        "\n",
271
                        "\n                   \t                  ",
272
                        trim($str)
273
                    )
274
                ),
275
                "\n";
276
        }
277
    }
278
 
279
    /**
280
     * Connect to an SMTP server.
281
     *
282
     * @param string $host    SMTP server IP or host name
283
     * @param int    $port    The port number to connect to
284
     * @param int    $timeout How long to wait for the connection to open
285
     * @param array  $options An array of options for stream_context_create()
286
     *
287
     * @return bool
288
     */
289
    public function connect($host, $port = null, $timeout = 30, $options = [])
290
    {
291
        static $streamok;
292
        //This is enabled by default since 5.0.0 but some providers disable it
293
        //Check this once and cache the result
294
        if (null === $streamok) {
295
            $streamok = function_exists('stream_socket_client');
296
        }
297
        // Clear errors to avoid confusion
298
        $this->setError('');
299
        // Make sure we are __not__ connected
300
        if ($this->connected()) {
301
            // Already connected, generate error
302
            $this->setError('Already connected to a server');
303
 
304
            return false;
305
        }
306
        if (empty($port)) {
307
            $port = self::DEFAULT_PORT;
308
        }
309
        // Connect to the SMTP server
310
        $this->edebug(
311
            "Connection: opening to $host:$port, timeout=$timeout, options=" .
312
            (count($options) > 0 ? var_export($options, true) : 'array()'),
313
            self::DEBUG_CONNECTION
314
        );
315
        $errno = 0;
316
        $errstr = '';
317
        if ($streamok) {
318
            $socket_context = stream_context_create($options);
319
            set_error_handler([$this, 'errorHandler']);
320
            $this->smtp_conn = stream_socket_client(
321
                $host . ':' . $port,
322
                $errno,
323
                $errstr,
324
                $timeout,
325
                STREAM_CLIENT_CONNECT,
326
                $socket_context
327
            );
328
            restore_error_handler();
329
        } else {
330
            //Fall back to fsockopen which should work in more places, but is missing some features
331
            $this->edebug(
332
                'Connection: stream_socket_client not available, falling back to fsockopen',
333
                self::DEBUG_CONNECTION
334
            );
335
            set_error_handler([$this, 'errorHandler']);
336
            $this->smtp_conn = fsockopen(
337
                $host,
338
                $port,
339
                $errno,
340
                $errstr,
341
                $timeout
342
            );
343
            restore_error_handler();
344
        }
345
        // Verify we connected properly
346
        if (!is_resource($this->smtp_conn)) {
347
            $this->setError(
348
                'Failed to connect to server',
349
                '',
350
                (string) $errno,
351
                (string) $errstr
352
            );
353
            $this->edebug(
354
                'SMTP ERROR: ' . $this->error['error']
355
                . ": $errstr ($errno)",
356
                self::DEBUG_CLIENT
357
            );
358
 
359
            return false;
360
        }
361
        $this->edebug('Connection: opened', self::DEBUG_CONNECTION);
362
        // SMTP server can take longer to respond, give longer timeout for first read
363
        // Windows does not have support for this timeout function
364
        if (substr(PHP_OS, 0, 3) != 'WIN') {
365
            $max = ini_get('max_execution_time');
366
            // Don't bother if unlimited
367
            if (0 != $max and $timeout > $max) {
368
                @set_time_limit($timeout);
369
            }
370
            stream_set_timeout($this->smtp_conn, $timeout, 0);
371
        }
372
        // Get any announcement
373
        $announce = $this->get_lines();
374
        $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
375
 
376
        return true;
377
    }
378
 
379
    /**
380
     * Initiate a TLS (encrypted) session.
381
     *
382
     * @return bool
383
     */
384
    public function startTLS()
385
    {
386
        if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
387
            return false;
388
        }
389
 
390
        //Allow the best TLS version(s) we can
391
        $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
392
 
393
        //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT
394
        //so add them back in manually if we can
395
        if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
396
            $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
397
            $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
398
        }
399
 
400
        // Begin encrypted connection
401
        set_error_handler([$this, 'errorHandler']);
402
        $crypto_ok = stream_socket_enable_crypto(
403
            $this->smtp_conn,
404
            true,
405
            $crypto_method
406
        );
407
        restore_error_handler();
408
 
409
        return (bool) $crypto_ok;
410
    }
411
 
412
    /**
413
     * Perform SMTP authentication.
414
     * Must be run after hello().
415
     *
416
     * @see    hello()
417
     *
418
     * @param string $username The user name
419
     * @param string $password The password
420
     * @param string $authtype The auth type (CRAM-MD5, PLAIN, LOGIN, XOAUTH2)
421
     * @param OAuth  $OAuth    An optional OAuth instance for XOAUTH2 authentication
422
     *
423
     * @return bool True if successfully authenticated
424
     */
425
    public function authenticate(
426
        $username,
427
        $password,
428
        $authtype = null,
429
        $OAuth = null
430
    ) {
431
        if (!$this->server_caps) {
432
            $this->setError('Authentication is not allowed before HELO/EHLO');
433
 
434
            return false;
435
        }
436
 
437
        if (array_key_exists('EHLO', $this->server_caps)) {
438
            // SMTP extensions are available; try to find a proper authentication method
439
            if (!array_key_exists('AUTH', $this->server_caps)) {
440
                $this->setError('Authentication is not allowed at this stage');
441
                // 'at this stage' means that auth may be allowed after the stage changes
442
                // e.g. after STARTTLS
443
 
444
                return false;
445
            }
446
 
447
            $this->edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNSPECIFIED'), self::DEBUG_LOWLEVEL);
448
            $this->edebug(
449
                'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
450
                self::DEBUG_LOWLEVEL
451
            );
452
 
453
            //If we have requested a specific auth type, check the server supports it before trying others
454
            if (null !== $authtype and !in_array($authtype, $this->server_caps['AUTH'])) {
455
                $this->edebug('Requested auth method not available: ' . $authtype, self::DEBUG_LOWLEVEL);
456
                $authtype = null;
457
            }
458
 
459
            if (empty($authtype)) {
460
                //If no auth mechanism is specified, attempt to use these, in this order
461
                //Try CRAM-MD5 first as it's more secure than the others
462
                foreach (['CRAM-MD5', 'LOGIN', 'PLAIN', 'XOAUTH2'] as $method) {
463
                    if (in_array($method, $this->server_caps['AUTH'])) {
464
                        $authtype = $method;
465
                        break;
466
                    }
467
                }
468
                if (empty($authtype)) {
469
                    $this->setError('No supported authentication methods found');
470
 
471
                    return false;
472
                }
473
                self::edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL);
474
            }
475
 
476
            if (!in_array($authtype, $this->server_caps['AUTH'])) {
477
                $this->setError("The requested authentication method \"$authtype\" is not supported by the server");
478
 
479
                return false;
480
            }
481
        } elseif (empty($authtype)) {
482
            $authtype = 'LOGIN';
483
        }
484
        switch ($authtype) {
485
            case 'PLAIN':
486
                // Start authentication
487
                if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
488
                    return false;
489
                }
490
                // Send encoded username and password
491
                if (!$this->sendCommand(
492
                    'User & Password',
493
                    base64_encode("\0" . $username . "\0" . $password),
494
                    235
495
                )
496
                ) {
497
                    return false;
498
                }
499
                break;
500
            case 'LOGIN':
501
                // Start authentication
502
                if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
503
                    return false;
504
                }
505
                if (!$this->sendCommand('Username', base64_encode($username), 334)) {
506
                    return false;
507
                }
508
                if (!$this->sendCommand('Password', base64_encode($password), 235)) {
509
                    return false;
510
                }
511
                break;
512
            case 'CRAM-MD5':
513
                // Start authentication
514
                if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
515
                    return false;
516
                }
517
                // Get the challenge
518
                $challenge = base64_decode(substr($this->last_reply, 4));
519
 
520
                // Build the response
521
                $response = $username . ' ' . $this->hmac($challenge, $password);
522
 
523
                // send encoded credentials
524
                return $this->sendCommand('Username', base64_encode($response), 235);
525
            case 'XOAUTH2':
526
                //The OAuth instance must be set up prior to requesting auth.
527
                if (null === $OAuth) {
528
                    return false;
529
                }
530
                $oauth = $OAuth->getOauth64();
531
 
532
                // Start authentication
533
                if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
534
                    return false;
535
                }
536
                break;
537
            default:
538
                $this->setError("Authentication method \"$authtype\" is not supported");
539
 
540
                return false;
541
        }
542
 
543
        return true;
544
    }
545
 
546
    /**
547
     * Calculate an MD5 HMAC hash.
548
     * Works like hash_hmac('md5', $data, $key)
549
     * in case that function is not available.
550
     *
551
     * @param string $data The data to hash
552
     * @param string $key  The key to hash with
553
     *
554
     * @return string
555
     */
556
    protected function hmac($data, $key)
557
    {
558
        if (function_exists('hash_hmac')) {
559
            return hash_hmac('md5', $data, $key);
560
        }
561
 
562
        // The following borrowed from
563
        // http://php.net/manual/en/function.mhash.php#27225
564
 
565
        // RFC 2104 HMAC implementation for php.
566
        // Creates an md5 HMAC.
567
        // Eliminates the need to install mhash to compute a HMAC
568
        // by Lance Rushing
569
 
570
        $bytelen = 64; // byte length for md5
571
        if (strlen($key) > $bytelen) {
572
            $key = pack('H*', md5($key));
573
        }
574
        $key = str_pad($key, $bytelen, chr(0x00));
575
        $ipad = str_pad('', $bytelen, chr(0x36));
576
        $opad = str_pad('', $bytelen, chr(0x5c));
577
        $k_ipad = $key ^ $ipad;
578
        $k_opad = $key ^ $opad;
579
 
580
        return md5($k_opad . pack('H*', md5($k_ipad . $data)));
581
    }
582
 
583
    /**
584
     * Check connection state.
585
     *
586
     * @return bool True if connected
587
     */
588
    public function connected()
589
    {
590
        if (is_resource($this->smtp_conn)) {
591
            $sock_status = stream_get_meta_data($this->smtp_conn);
592
            if ($sock_status['eof']) {
593
                // The socket is valid but we are not connected
594
                $this->edebug(
595
                    'SMTP NOTICE: EOF caught while checking if connected',
596
                    self::DEBUG_CLIENT
597
                );
598
                $this->close();
599
 
600
                return false;
601
            }
602
 
603
            return true; // everything looks good
604
        }
605
 
606
        return false;
607
    }
608
 
609
    /**
610
     * Close the socket and clean up the state of the class.
611
     * Don't use this function without first trying to use QUIT.
612
     *
613
     * @see quit()
614
     */
615
    public function close()
616
    {
617
        $this->setError('');
618
        $this->server_caps = null;
619
        $this->helo_rply = null;
620
        if (is_resource($this->smtp_conn)) {
621
            // close the connection and cleanup
622
            fclose($this->smtp_conn);
623
            $this->smtp_conn = null; //Makes for cleaner serialization
624
            $this->edebug('Connection: closed', self::DEBUG_CONNECTION);
625
        }
626
    }
627
 
628
    /**
629
     * Send an SMTP DATA command.
630
     * Issues a data command and sends the msg_data to the server,
631
     * finializing the mail transaction. $msg_data is the message
632
     * that is to be send with the headers. Each header needs to be
633
     * on a single line followed by a <CRLF> with the message headers
634
     * and the message body being separated by an additional <CRLF>.
635
     * Implements RFC 821: DATA <CRLF>.
636
     *
637
     * @param string $msg_data Message data to send
638
     *
639
     * @return bool
640
     */
641
    public function data($msg_data)
642
    {
643
        //This will use the standard timelimit
644
        if (!$this->sendCommand('DATA', 'DATA', 354)) {
645
            return false;
646
        }
647
 
648
        /* The server is ready to accept data!
649
         * According to rfc821 we should not send more than 1000 characters on a single line (including the LE)
650
         * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
651
         * smaller lines to fit within the limit.
652
         * We will also look for lines that start with a '.' and prepend an additional '.'.
653
         * NOTE: this does not count towards line-length limit.
654
         */
655
 
656
        // Normalize line breaks before exploding
657
        $lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $msg_data));
658
 
659
        /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
660
         * of the first line (':' separated) does not contain a space then it _should_ be a header and we will
661
         * process all lines before a blank line as headers.
662
         */
663
 
664
        $field = substr($lines[0], 0, strpos($lines[0], ':'));
665
        $in_headers = false;
666
        if (!empty($field) and strpos($field, ' ') === false) {
667
            $in_headers = true;
668
        }
669
 
670
        foreach ($lines as $line) {
671
            $lines_out = [];
672
            if ($in_headers and $line == '') {
673
                $in_headers = false;
674
            }
675
            //Break this line up into several smaller lines if it's too long
676
            //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
677
            while (isset($line[self::MAX_LINE_LENGTH])) {
678
                //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
679
                //so as to avoid breaking in the middle of a word
680
                $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
681
                //Deliberately matches both false and 0
682
                if (!$pos) {
683
                    //No nice break found, add a hard break
684
                    $pos = self::MAX_LINE_LENGTH - 1;
685
                    $lines_out[] = substr($line, 0, $pos);
686
                    $line = substr($line, $pos);
687
                } else {
688
                    //Break at the found point
689
                    $lines_out[] = substr($line, 0, $pos);
690
                    //Move along by the amount we dealt with
691
                    $line = substr($line, $pos + 1);
692
                }
693
                //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
694
                if ($in_headers) {
695
                    $line = "\t" . $line;
696
                }
697
            }
698
            $lines_out[] = $line;
699
 
700
            //Send the lines to the server
701
            foreach ($lines_out as $line_out) {
702
                //RFC2821 section 4.5.2
703
                if (!empty($line_out) and $line_out[0] == '.') {
704
                    $line_out = '.' . $line_out;
705
                }
706
                $this->client_send($line_out . static::LE, 'DATA');
707
            }
708
        }
709
 
710
        //Message data has been sent, complete the command
711
        //Increase timelimit for end of DATA command
712
        $savetimelimit = $this->Timelimit;
713
        $this->Timelimit = $this->Timelimit * 2;
714
        $result = $this->sendCommand('DATA END', '.', 250);
715
        $this->recordLastTransactionID();
716
        //Restore timelimit
717
        $this->Timelimit = $savetimelimit;
718
 
719
        return $result;
720
    }
721
 
722
    /**
723
     * Send an SMTP HELO or EHLO command.
724
     * Used to identify the sending server to the receiving server.
725
     * This makes sure that client and server are in a known state.
726
     * Implements RFC 821: HELO <SP> <domain> <CRLF>
727
     * and RFC 2821 EHLO.
728
     *
729
     * @param string $host The host name or IP to connect to
730
     *
731
     * @return bool
732
     */
733
    public function hello($host = '')
734
    {
735
        //Try extended hello first (RFC 2821)
736
        return $this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host);
737
    }
738
 
739
    /**
740
     * Send an SMTP HELO or EHLO command.
741
     * Low-level implementation used by hello().
742
     *
743
     * @param string $hello The HELO string
744
     * @param string $host  The hostname to say we are
745
     *
746
     * @return bool
747
     *
748
     * @see    hello()
749
     */
750
    protected function sendHello($hello, $host)
751
    {
752
        $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
753
        $this->helo_rply = $this->last_reply;
754
        if ($noerror) {
755
            $this->parseHelloFields($hello);
756
        } else {
757
            $this->server_caps = null;
758
        }
759
 
760
        return $noerror;
761
    }
762
 
763
    /**
764
     * Parse a reply to HELO/EHLO command to discover server extensions.
765
     * In case of HELO, the only parameter that can be discovered is a server name.
766
     *
767
     * @param string $type `HELO` or `EHLO`
768
     */
769
    protected function parseHelloFields($type)
770
    {
771
        $this->server_caps = [];
772
        $lines = explode("\n", $this->helo_rply);
773
 
774
        foreach ($lines as $n => $s) {
775
            //First 4 chars contain response code followed by - or space
776
            $s = trim(substr($s, 4));
777
            if (empty($s)) {
778
                continue;
779
            }
780
            $fields = explode(' ', $s);
781
            if (!empty($fields)) {
782
                if (!$n) {
783
                    $name = $type;
784
                    $fields = $fields[0];
785
                } else {
786
                    $name = array_shift($fields);
787
                    switch ($name) {
788
                        case 'SIZE':
789
                            $fields = ($fields ? $fields[0] : 0);
790
                            break;
791
                        case 'AUTH':
792
                            if (!is_array($fields)) {
793
                                $fields = [];
794
                            }
795
                            break;
796
                        default:
797
                            $fields = true;
798
                    }
799
                }
800
                $this->server_caps[$name] = $fields;
801
            }
802
        }
803
    }
804
 
805
    /**
806
     * Send an SMTP MAIL command.
807
     * Starts a mail transaction from the email address specified in
808
     * $from. Returns true if successful or false otherwise. If True
809
     * the mail transaction is started and then one or more recipient
810
     * commands may be called followed by a data command.
811
     * Implements RFC 821: MAIL <SP> FROM:<reverse-path> <CRLF>.
812
     *
813
     * @param string $from Source address of this message
814
     *
815
     * @return bool
816
     */
817
    public function mail($from)
818
    {
819
        $useVerp = ($this->do_verp ? ' XVERP' : '');
820
 
821
        return $this->sendCommand(
822
            'MAIL FROM',
823
            'MAIL FROM:<' . $from . '>' . $useVerp,
824
            250
825
        );
826
    }
827
 
828
    /**
829
     * Send an SMTP QUIT command.
830
     * Closes the socket if there is no error or the $close_on_error argument is true.
831
     * Implements from RFC 821: QUIT <CRLF>.
832
     *
833
     * @param bool $close_on_error Should the connection close if an error occurs?
834
     *
835
     * @return bool
836
     */
837
    public function quit($close_on_error = true)
838
    {
839
        $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
840
        $err = $this->error; //Save any error
841
        if ($noerror or $close_on_error) {
842
            $this->close();
843
            $this->error = $err; //Restore any error from the quit command
844
        }
845
 
846
        return $noerror;
847
    }
848
 
849
    /**
850
     * Send an SMTP RCPT command.
851
     * Sets the TO argument to $toaddr.
852
     * Returns true if the recipient was accepted false if it was rejected.
853
     * Implements from RFC 821: RCPT <SP> TO:<forward-path> <CRLF>.
854
     *
855
     * @param string $address The address the message is being sent to
73 - 856
     * @param string $dsn     Comma separated list of DSN notifications. NEVER, SUCCESS, FAILURE
857
     *                        or DELAY. If you specify NEVER all other notifications are ignored.
25 - 858
     *
859
     * @return bool
860
     */
73 - 861
    public function recipient($address, $dsn = '')
25 - 862
    {
73 - 863
        if (empty($dsn)) {
864
            $rcpt = 'RCPT TO:<' . $address . '>';
865
        } else {
866
            $dsn = strtoupper($dsn);
867
            $notify = [];
868
 
869
            if (strpos($dsn, 'NEVER') !== false) {
870
                $notify[] = 'NEVER';
871
            } else {
872
                foreach (['SUCCESS', 'FAILURE', 'DELAY'] as $value) {
873
                    if (strpos($dsn, $value) !== false) {
874
                        $notify[] = $value;
875
                    }
876
                }
877
            }
878
 
879
            $rcpt = 'RCPT TO:<' . $address . '> NOTIFY=' . implode(',', $notify);
880
        }
881
 
25 - 882
        return $this->sendCommand(
73 - 883
           'RCPT TO',
884
           $rcpt,
885
           [250, 251]
886
       );
25 - 887
    }
888
 
889
    /**
890
     * Send an SMTP RSET command.
891
     * Abort any transaction that is currently in progress.
892
     * Implements RFC 821: RSET <CRLF>.
893
     *
894
     * @return bool True on success
895
     */
896
    public function reset()
897
    {
898
        return $this->sendCommand('RSET', 'RSET', 250);
899
    }
900
 
901
    /**
902
     * Send a command to an SMTP server and check its return code.
903
     *
904
     * @param string    $command       The command name - not sent to the server
905
     * @param string    $commandstring The actual command to send
906
     * @param int|array $expect        One or more expected integer success codes
907
     *
908
     * @return bool True on success
909
     */
910
    protected function sendCommand($command, $commandstring, $expect)
911
    {
912
        if (!$this->connected()) {
913
            $this->setError("Called $command without being connected");
914
 
915
            return false;
916
        }
917
        //Reject line breaks in all commands
918
        if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) {
919
            $this->setError("Command '$command' contained line breaks");
920
 
921
            return false;
922
        }
923
        $this->client_send($commandstring . static::LE, $command);
924
 
925
        $this->last_reply = $this->get_lines();
926
        // Fetch SMTP code and possible error code explanation
927
        $matches = [];
73 - 928
        if (preg_match('/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]{1,2}) )?/', $this->last_reply, $matches)) {
25 - 929
            $code = $matches[1];
930
            $code_ex = (count($matches) > 2 ? $matches[2] : null);
931
            // Cut off error code from each response line
932
            $detail = preg_replace(
933
                "/{$code}[ -]" .
934
                ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . '/m',
935
                '',
936
                $this->last_reply
937
            );
938
        } else {
939
            // Fall back to simple parsing if regex fails
940
            $code = substr($this->last_reply, 0, 3);
941
            $code_ex = null;
942
            $detail = substr($this->last_reply, 4);
943
        }
944
 
945
        $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
946
 
947
        if (!in_array($code, (array) $expect)) {
948
            $this->setError(
949
                "$command command failed",
950
                $detail,
951
                $code,
952
                $code_ex
953
            );
954
            $this->edebug(
955
                'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,
956
                self::DEBUG_CLIENT
957
            );
958
 
959
            return false;
960
        }
961
 
962
        $this->setError('');
963
 
964
        return true;
965
    }
966
 
967
    /**
968
     * Send an SMTP SAML command.
969
     * Starts a mail transaction from the email address specified in $from.
970
     * Returns true if successful or false otherwise. If True
971
     * the mail transaction is started and then one or more recipient
972
     * commands may be called followed by a data command. This command
973
     * will send the message to the users terminal if they are logged
974
     * in and send them an email.
975
     * Implements RFC 821: SAML <SP> FROM:<reverse-path> <CRLF>.
976
     *
977
     * @param string $from The address the message is from
978
     *
979
     * @return bool
980
     */
981
    public function sendAndMail($from)
982
    {
983
        return $this->sendCommand('SAML', "SAML FROM:$from", 250);
984
    }
985
 
986
    /**
987
     * Send an SMTP VRFY command.
988
     *
989
     * @param string $name The name to verify
990
     *
991
     * @return bool
992
     */
993
    public function verify($name)
994
    {
995
        return $this->sendCommand('VRFY', "VRFY $name", [250, 251]);
996
    }
997
 
998
    /**
999
     * Send an SMTP NOOP command.
1000
     * Used to keep keep-alives alive, doesn't actually do anything.
1001
     *
1002
     * @return bool
1003
     */
1004
    public function noop()
1005
    {
1006
        return $this->sendCommand('NOOP', 'NOOP', 250);
1007
    }
1008
 
1009
    /**
1010
     * Send an SMTP TURN command.
1011
     * This is an optional command for SMTP that this class does not support.
1012
     * This method is here to make the RFC821 Definition complete for this class
1013
     * and _may_ be implemented in future.
1014
     * Implements from RFC 821: TURN <CRLF>.
1015
     *
1016
     * @return bool
1017
     */
1018
    public function turn()
1019
    {
1020
        $this->setError('The SMTP TURN command is not implemented');
1021
        $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
1022
 
1023
        return false;
1024
    }
1025
 
1026
    /**
1027
     * Send raw data to the server.
1028
     *
1029
     * @param string $data    The data to send
1030
     * @param string $command Optionally, the command this is part of, used only for controlling debug output
1031
     *
1032
     * @return int|bool The number of bytes sent to the server or false on error
1033
     */
1034
    public function client_send($data, $command = '')
1035
    {
1036
        //If SMTP transcripts are left enabled, or debug output is posted online
1037
        //it can leak credentials, so hide credentials in all but lowest level
1038
        if (self::DEBUG_LOWLEVEL > $this->do_debug and
1039
            in_array($command, ['User & Password', 'Username', 'Password'], true)) {
1040
            $this->edebug('CLIENT -> SERVER: <credentials hidden>', self::DEBUG_CLIENT);
1041
        } else {
1042
            $this->edebug('CLIENT -> SERVER: ' . $data, self::DEBUG_CLIENT);
1043
        }
1044
        set_error_handler([$this, 'errorHandler']);
1045
        $result = fwrite($this->smtp_conn, $data);
1046
        restore_error_handler();
1047
 
1048
        return $result;
1049
    }
1050
 
1051
    /**
1052
     * Get the latest error.
1053
     *
1054
     * @return array
1055
     */
1056
    public function getError()
1057
    {
1058
        return $this->error;
1059
    }
1060
 
1061
    /**
1062
     * Get SMTP extensions available on the server.
1063
     *
1064
     * @return array|null
1065
     */
1066
    public function getServerExtList()
1067
    {
1068
        return $this->server_caps;
1069
    }
1070
 
1071
    /**
1072
     * Get metadata about the SMTP server from its HELO/EHLO response.
1073
     * The method works in three ways, dependent on argument value and current state:
1074
     *   1. HELO/EHLO has not been sent - returns null and populates $this->error.
1075
     *   2. HELO has been sent -
1076
     *     $name == 'HELO': returns server name
1077
     *     $name == 'EHLO': returns boolean false
1078
     *     $name == any other string: returns null and populates $this->error
1079
     *   3. EHLO has been sent -
1080
     *     $name == 'HELO'|'EHLO': returns the server name
1081
     *     $name == any other string: if extension $name exists, returns True
1082
     *       or its options (e.g. AUTH mechanisms supported). Otherwise returns False.
1083
     *
1084
     * @param string $name Name of SMTP extension or 'HELO'|'EHLO'
1085
     *
1086
     * @return mixed
1087
     */
1088
    public function getServerExt($name)
1089
    {
1090
        if (!$this->server_caps) {
1091
            $this->setError('No HELO/EHLO was sent');
1092
 
1093
            return;
1094
        }
1095
 
1096
        if (!array_key_exists($name, $this->server_caps)) {
1097
            if ('HELO' == $name) {
1098
                return $this->server_caps['EHLO'];
1099
            }
1100
            if ('EHLO' == $name || array_key_exists('EHLO', $this->server_caps)) {
1101
                return false;
1102
            }
1103
            $this->setError('HELO handshake was used; No information about server extensions available');
1104
 
1105
            return;
1106
        }
1107
 
1108
        return $this->server_caps[$name];
1109
    }
1110
 
1111
    /**
1112
     * Get the last reply from the server.
1113
     *
1114
     * @return string
1115
     */
1116
    public function getLastReply()
1117
    {
1118
        return $this->last_reply;
1119
    }
1120
 
1121
    /**
1122
     * Read the SMTP server's response.
1123
     * Either before eof or socket timeout occurs on the operation.
1124
     * With SMTP we can tell if we have more lines to read if the
1125
     * 4th character is '-' symbol. If it is a space then we don't
1126
     * need to read anything else.
1127
     *
1128
     * @return string
1129
     */
1130
    protected function get_lines()
1131
    {
1132
        // If the connection is bad, give up straight away
1133
        if (!is_resource($this->smtp_conn)) {
1134
            return '';
1135
        }
1136
        $data = '';
1137
        $endtime = 0;
1138
        stream_set_timeout($this->smtp_conn, $this->Timeout);
1139
        if ($this->Timelimit > 0) {
1140
            $endtime = time() + $this->Timelimit;
1141
        }
1142
        $selR = [$this->smtp_conn];
1143
        $selW = null;
1144
        while (is_resource($this->smtp_conn) and !feof($this->smtp_conn)) {
1145
            //Must pass vars in here as params are by reference
1146
            if (!stream_select($selR, $selW, $selW, $this->Timelimit)) {
1147
                $this->edebug(
1148
                    'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
1149
                    self::DEBUG_LOWLEVEL
1150
                );
1151
                break;
1152
            }
1153
            //Deliberate noise suppression - errors are handled afterwards
1154
            $str = @fgets($this->smtp_conn, 515);
1155
            $this->edebug('SMTP INBOUND: "' . trim($str) . '"', self::DEBUG_LOWLEVEL);
1156
            $data .= $str;
1157
            // If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled),
1158
            // or 4th character is a space, we are done reading, break the loop,
1159
            // string array access is a micro-optimisation over strlen
1160
            if (!isset($str[3]) or (isset($str[3]) and $str[3] == ' ')) {
1161
                break;
1162
            }
1163
            // Timed-out? Log and break
1164
            $info = stream_get_meta_data($this->smtp_conn);
1165
            if ($info['timed_out']) {
1166
                $this->edebug(
1167
                    'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
1168
                    self::DEBUG_LOWLEVEL
1169
                );
1170
                break;
1171
            }
1172
            // Now check if reads took too long
1173
            if ($endtime and time() > $endtime) {
1174
                $this->edebug(
1175
                    'SMTP -> get_lines(): timelimit reached (' .
1176
                    $this->Timelimit . ' sec)',
1177
                    self::DEBUG_LOWLEVEL
1178
                );
1179
                break;
1180
            }
1181
        }
1182
 
1183
        return $data;
1184
    }
1185
 
1186
    /**
1187
     * Enable or disable VERP address generation.
1188
     *
1189
     * @param bool $enabled
1190
     */
1191
    public function setVerp($enabled = false)
1192
    {
1193
        $this->do_verp = $enabled;
1194
    }
1195
 
1196
    /**
1197
     * Get VERP address generation mode.
1198
     *
1199
     * @return bool
1200
     */
1201
    public function getVerp()
1202
    {
1203
        return $this->do_verp;
1204
    }
1205
 
1206
    /**
1207
     * Set error messages and codes.
1208
     *
1209
     * @param string $message      The error message
1210
     * @param string $detail       Further detail on the error
1211
     * @param string $smtp_code    An associated SMTP error code
1212
     * @param string $smtp_code_ex Extended SMTP code
1213
     */
1214
    protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
1215
    {
1216
        $this->error = [
1217
            'error' => $message,
1218
            'detail' => $detail,
1219
            'smtp_code' => $smtp_code,
1220
            'smtp_code_ex' => $smtp_code_ex,
1221
        ];
1222
    }
1223
 
1224
    /**
1225
     * Set debug output method.
1226
     *
1227
     * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it
1228
     */
1229
    public function setDebugOutput($method = 'echo')
1230
    {
1231
        $this->Debugoutput = $method;
1232
    }
1233
 
1234
    /**
1235
     * Get debug output method.
1236
     *
1237
     * @return string
1238
     */
1239
    public function getDebugOutput()
1240
    {
1241
        return $this->Debugoutput;
1242
    }
1243
 
1244
    /**
1245
     * Set debug output level.
1246
     *
1247
     * @param int $level
1248
     */
1249
    public function setDebugLevel($level = 0)
1250
    {
1251
        $this->do_debug = $level;
1252
    }
1253
 
1254
    /**
1255
     * Get debug output level.
1256
     *
1257
     * @return int
1258
     */
1259
    public function getDebugLevel()
1260
    {
1261
        return $this->do_debug;
1262
    }
1263
 
1264
    /**
1265
     * Set SMTP timeout.
1266
     *
1267
     * @param int $timeout The timeout duration in seconds
1268
     */
1269
    public function setTimeout($timeout = 0)
1270
    {
1271
        $this->Timeout = $timeout;
1272
    }
1273
 
1274
    /**
1275
     * Get SMTP timeout.
1276
     *
1277
     * @return int
1278
     */
1279
    public function getTimeout()
1280
    {
1281
        return $this->Timeout;
1282
    }
1283
 
1284
    /**
1285
     * Reports an error number and string.
1286
     *
1287
     * @param int    $errno   The error number returned by PHP
1288
     * @param string $errmsg  The error message returned by PHP
1289
     * @param string $errfile The file the error occurred in
1290
     * @param int    $errline The line number the error occurred on
1291
     */
1292
    protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0)
1293
    {
1294
        $notice = 'Connection failed.';
1295
        $this->setError(
1296
            $notice,
1297
            $errmsg,
1298
            (string) $errno
1299
        );
1300
        $this->edebug(
1301
            "$notice Error #$errno: $errmsg [$errfile line $errline]",
1302
            self::DEBUG_CONNECTION
1303
        );
1304
    }
1305
 
1306
    /**
1307
     * Extract and return the ID of the last SMTP transaction based on
1308
     * a list of patterns provided in SMTP::$smtp_transaction_id_patterns.
1309
     * Relies on the host providing the ID in response to a DATA command.
1310
     * If no reply has been received yet, it will return null.
1311
     * If no pattern was matched, it will return false.
1312
     *
73 - 1313
     * @return bool|string|null
25 - 1314
     */
1315
    protected function recordLastTransactionID()
1316
    {
1317
        $reply = $this->getLastReply();
1318
 
1319
        if (empty($reply)) {
1320
            $this->last_smtp_transaction_id = null;
1321
        } else {
1322
            $this->last_smtp_transaction_id = false;
1323
            foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
1324
                if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
1325
                    $this->last_smtp_transaction_id = trim($matches[1]);
1326
                    break;
1327
                }
1328
            }
1329
        }
1330
 
1331
        return $this->last_smtp_transaction_id;
1332
    }
1333
 
1334
    /**
1335
     * Get the queue/transaction ID of the last SMTP transaction
1336
     * If no reply has been received yet, it will return null.
1337
     * If no pattern was matched, it will return false.
1338
     *
73 - 1339
     * @return bool|string|null
25 - 1340
     *
1341
     * @see recordLastTransactionID()
1342
     */
1343
    public function getLastTransactionID()
1344
    {
1345
        return $this->last_smtp_transaction_id;
1346
    }
73 - 1347
}