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