Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

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