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