SMTP.php 45 KB

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