SMTP.php 46 KB

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