SMTP.php 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  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.7.1';
  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. 'Haraka' => '/[\d]{3} Message Queued \((.*)\)/',
  172. 'Mailjet' => '/[\d]{3} OK queued as (.*)/',
  173. ];
  174. /**
  175. * The last transaction ID issued in response to a DATA command,
  176. * if one was detected.
  177. *
  178. * @var string|bool|null
  179. */
  180. protected $last_smtp_transaction_id;
  181. /**
  182. * The socket for the server connection.
  183. *
  184. * @var ?resource
  185. */
  186. protected $smtp_conn;
  187. /**
  188. * Error information, if any, for the last SMTP command.
  189. *
  190. * @var array
  191. */
  192. protected $error = [
  193. 'error' => '',
  194. 'detail' => '',
  195. 'smtp_code' => '',
  196. 'smtp_code_ex' => '',
  197. ];
  198. /**
  199. * The reply the server sent to us for HELO.
  200. * If null, no HELO string has yet been received.
  201. *
  202. * @var string|null
  203. */
  204. protected $helo_rply;
  205. /**
  206. * The set of SMTP extensions sent in reply to EHLO command.
  207. * Indexes of the array are extension names.
  208. * Value at index 'HELO' or 'EHLO' (according to command that was sent)
  209. * represents the server name. In case of HELO it is the only element of the array.
  210. * Other values can be boolean TRUE or an array containing extension options.
  211. * If null, no HELO/EHLO string has yet been received.
  212. *
  213. * @var array|null
  214. */
  215. protected $server_caps;
  216. /**
  217. * The most recent reply received from the server.
  218. *
  219. * @var string
  220. */
  221. protected $last_reply = '';
  222. /**
  223. * Output debugging info via a user-selected method.
  224. *
  225. * @param string $str Debug string to output
  226. * @param int $level The debug level of this message; see DEBUG_* constants
  227. *
  228. * @see SMTP::$Debugoutput
  229. * @see SMTP::$do_debug
  230. */
  231. protected function edebug($str, $level = 0)
  232. {
  233. if ($level > $this->do_debug) {
  234. return;
  235. }
  236. //Is this a PSR-3 logger?
  237. if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) {
  238. $this->Debugoutput->debug($str);
  239. return;
  240. }
  241. //Avoid clash with built-in function names
  242. if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) {
  243. call_user_func($this->Debugoutput, $str, $level);
  244. return;
  245. }
  246. switch ($this->Debugoutput) {
  247. case 'error_log':
  248. //Don't output, just log
  249. error_log($str);
  250. break;
  251. case 'html':
  252. //Cleans up output a bit for a better looking, HTML-safe output
  253. echo gmdate('Y-m-d H:i:s'), ' ', htmlentities(
  254. preg_replace('/[\r\n]+/', '', $str),
  255. ENT_QUOTES,
  256. 'UTF-8'
  257. ), "<br>\n";
  258. break;
  259. case 'echo':
  260. default:
  261. //Normalize line breaks
  262. $str = preg_replace('/\r\n|\r/m', "\n", $str);
  263. echo gmdate('Y-m-d H:i:s'),
  264. "\t",
  265. //Trim trailing space
  266. trim(
  267. //Indent for readability, except for trailing break
  268. str_replace(
  269. "\n",
  270. "\n \t ",
  271. trim($str)
  272. )
  273. ),
  274. "\n";
  275. }
  276. }
  277. /**
  278. * Connect to an SMTP server.
  279. *
  280. * @param string $host SMTP server IP or host name
  281. * @param int $port The port number to connect to
  282. * @param int $timeout How long to wait for the connection to open
  283. * @param array $options An array of options for stream_context_create()
  284. *
  285. * @return bool
  286. */
  287. public function connect($host, $port = null, $timeout = 30, $options = [])
  288. {
  289. //Clear errors to avoid confusion
  290. $this->setError('');
  291. //Make sure we are __not__ connected
  292. if ($this->connected()) {
  293. //Already connected, generate error
  294. $this->setError('Already connected to a server');
  295. return false;
  296. }
  297. if (empty($port)) {
  298. $port = self::DEFAULT_PORT;
  299. }
  300. //Connect to the SMTP server
  301. $this->edebug(
  302. "Connection: opening to $host:$port, timeout=$timeout, options=" .
  303. (count($options) > 0 ? var_export($options, true) : 'array()'),
  304. self::DEBUG_CONNECTION
  305. );
  306. $this->smtp_conn = $this->getSMTPConnection($host, $port, $timeout, $options);
  307. if ($this->smtp_conn === false) {
  308. //Error info already set inside `getSMTPConnection()`
  309. return false;
  310. }
  311. $this->edebug('Connection: opened', self::DEBUG_CONNECTION);
  312. //Get any announcement
  313. $this->last_reply = $this->get_lines();
  314. $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
  315. $responseCode = (int)substr($this->last_reply, 0, 3);
  316. if ($responseCode === 220) {
  317. return true;
  318. }
  319. //Anything other than a 220 response means something went wrong
  320. //RFC 5321 says the server will wait for us to send a QUIT in response to a 554 error
  321. //https://tools.ietf.org/html/rfc5321#section-3.1
  322. if ($responseCode === 554) {
  323. $this->quit();
  324. }
  325. //This will handle 421 responses which may not wait for a QUIT (e.g. if the server is being shut down)
  326. $this->edebug('Connection: closing due to error', self::DEBUG_CONNECTION);
  327. $this->close();
  328. return false;
  329. }
  330. /**
  331. * Create connection to the SMTP server.
  332. *
  333. * @param string $host SMTP server IP or host name
  334. * @param int $port The port number to connect to
  335. * @param int $timeout How long to wait for the connection to open
  336. * @param array $options An array of options for stream_context_create()
  337. *
  338. * @return false|resource
  339. */
  340. protected function getSMTPConnection($host, $port = null, $timeout = 30, $options = [])
  341. {
  342. static $streamok;
  343. //This is enabled by default since 5.0.0 but some providers disable it
  344. //Check this once and cache the result
  345. if (null === $streamok) {
  346. $streamok = function_exists('stream_socket_client');
  347. }
  348. $errno = 0;
  349. $errstr = '';
  350. if ($streamok) {
  351. $socket_context = stream_context_create($options);
  352. set_error_handler([$this, 'errorHandler']);
  353. $connection = stream_socket_client(
  354. $host . ':' . $port,
  355. $errno,
  356. $errstr,
  357. $timeout,
  358. STREAM_CLIENT_CONNECT,
  359. $socket_context
  360. );
  361. } else {
  362. //Fall back to fsockopen which should work in more places, but is missing some features
  363. $this->edebug(
  364. 'Connection: stream_socket_client not available, falling back to fsockopen',
  365. self::DEBUG_CONNECTION
  366. );
  367. set_error_handler([$this, 'errorHandler']);
  368. $connection = fsockopen(
  369. $host,
  370. $port,
  371. $errno,
  372. $errstr,
  373. $timeout
  374. );
  375. }
  376. restore_error_handler();
  377. //Verify we connected properly
  378. if (!is_resource($connection)) {
  379. $this->setError(
  380. 'Failed to connect to server',
  381. '',
  382. (string) $errno,
  383. $errstr
  384. );
  385. $this->edebug(
  386. 'SMTP ERROR: ' . $this->error['error']
  387. . ": $errstr ($errno)",
  388. self::DEBUG_CLIENT
  389. );
  390. return false;
  391. }
  392. //SMTP server can take longer to respond, give longer timeout for first read
  393. //Windows does not have support for this timeout function
  394. if (strpos(PHP_OS, 'WIN') !== 0) {
  395. $max = (int)ini_get('max_execution_time');
  396. //Don't bother if unlimited, or if set_time_limit is disabled
  397. if (0 !== $max && $timeout > $max && strpos(ini_get('disable_functions'), 'set_time_limit') === false) {
  398. @set_time_limit($timeout);
  399. }
  400. stream_set_timeout($connection, $timeout, 0);
  401. }
  402. return $connection;
  403. }
  404. /**
  405. * Initiate a TLS (encrypted) session.
  406. *
  407. * @return bool
  408. */
  409. public function startTLS()
  410. {
  411. if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
  412. return false;
  413. }
  414. //Allow the best TLS version(s) we can
  415. $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
  416. //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT
  417. //so add them back in manually if we can
  418. if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
  419. $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
  420. $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
  421. }
  422. //Begin encrypted connection
  423. set_error_handler([$this, 'errorHandler']);
  424. $crypto_ok = stream_socket_enable_crypto(
  425. $this->smtp_conn,
  426. true,
  427. $crypto_method
  428. );
  429. restore_error_handler();
  430. return (bool) $crypto_ok;
  431. }
  432. /**
  433. * Perform SMTP authentication.
  434. * Must be run after hello().
  435. *
  436. * @see hello()
  437. *
  438. * @param string $username The user name
  439. * @param string $password The password
  440. * @param string $authtype The auth type (CRAM-MD5, PLAIN, LOGIN, XOAUTH2)
  441. * @param OAuthTokenProvider $OAuth An optional OAuthTokenProvider instance for XOAUTH2 authentication
  442. *
  443. * @return bool True if successfully authenticated
  444. */
  445. public function authenticate(
  446. $username,
  447. $password,
  448. $authtype = null,
  449. $OAuth = null
  450. ) {
  451. if (!$this->server_caps) {
  452. $this->setError('Authentication is not allowed before HELO/EHLO');
  453. return false;
  454. }
  455. if (array_key_exists('EHLO', $this->server_caps)) {
  456. //SMTP extensions are available; try to find a proper authentication method
  457. if (!array_key_exists('AUTH', $this->server_caps)) {
  458. $this->setError('Authentication is not allowed at this stage');
  459. //'at this stage' means that auth may be allowed after the stage changes
  460. //e.g. after STARTTLS
  461. return false;
  462. }
  463. $this->edebug('Auth method requested: ' . ($authtype ?: 'UNSPECIFIED'), self::DEBUG_LOWLEVEL);
  464. $this->edebug(
  465. 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
  466. self::DEBUG_LOWLEVEL
  467. );
  468. //If we have requested a specific auth type, check the server supports it before trying others
  469. if (null !== $authtype && !in_array($authtype, $this->server_caps['AUTH'], true)) {
  470. $this->edebug('Requested auth method not available: ' . $authtype, self::DEBUG_LOWLEVEL);
  471. $authtype = null;
  472. }
  473. if (empty($authtype)) {
  474. //If no auth mechanism is specified, attempt to use these, in this order
  475. //Try CRAM-MD5 first as it's more secure than the others
  476. foreach (['CRAM-MD5', 'LOGIN', 'PLAIN', 'XOAUTH2'] as $method) {
  477. if (in_array($method, $this->server_caps['AUTH'], true)) {
  478. $authtype = $method;
  479. break;
  480. }
  481. }
  482. if (empty($authtype)) {
  483. $this->setError('No supported authentication methods found');
  484. return false;
  485. }
  486. $this->edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL);
  487. }
  488. if (!in_array($authtype, $this->server_caps['AUTH'], true)) {
  489. $this->setError("The requested authentication method \"$authtype\" is not supported by the server");
  490. return false;
  491. }
  492. } elseif (empty($authtype)) {
  493. $authtype = 'LOGIN';
  494. }
  495. switch ($authtype) {
  496. case 'PLAIN':
  497. //Start authentication
  498. if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
  499. return false;
  500. }
  501. //Send encoded username and password
  502. if (
  503. //Format from https://tools.ietf.org/html/rfc4616#section-2
  504. //We skip the first field (it's forgery), so the string starts with a null byte
  505. !$this->sendCommand(
  506. 'User & Password',
  507. base64_encode("\0" . $username . "\0" . $password),
  508. 235
  509. )
  510. ) {
  511. return false;
  512. }
  513. break;
  514. case 'LOGIN':
  515. //Start authentication
  516. if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
  517. return false;
  518. }
  519. if (!$this->sendCommand('Username', base64_encode($username), 334)) {
  520. return false;
  521. }
  522. if (!$this->sendCommand('Password', base64_encode($password), 235)) {
  523. return false;
  524. }
  525. break;
  526. case 'CRAM-MD5':
  527. //Start authentication
  528. if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
  529. return false;
  530. }
  531. //Get the challenge
  532. $challenge = base64_decode(substr($this->last_reply, 4));
  533. //Build the response
  534. $response = $username . ' ' . $this->hmac($challenge, $password);
  535. //send encoded credentials
  536. return $this->sendCommand('Username', base64_encode($response), 235);
  537. case 'XOAUTH2':
  538. //The OAuth instance must be set up prior to requesting auth.
  539. if (null === $OAuth) {
  540. return false;
  541. }
  542. $oauth = $OAuth->getOauth64();
  543. //Start authentication
  544. if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
  545. return false;
  546. }
  547. break;
  548. default:
  549. $this->setError("Authentication method \"$authtype\" is not supported");
  550. return false;
  551. }
  552. return true;
  553. }
  554. /**
  555. * Calculate an MD5 HMAC hash.
  556. * Works like hash_hmac('md5', $data, $key)
  557. * in case that function is not available.
  558. *
  559. * @param string $data The data to hash
  560. * @param string $key The key to hash with
  561. *
  562. * @return string
  563. */
  564. protected function hmac($data, $key)
  565. {
  566. if (function_exists('hash_hmac')) {
  567. return hash_hmac('md5', $data, $key);
  568. }
  569. //The following borrowed from
  570. //http://php.net/manual/en/function.mhash.php#27225
  571. //RFC 2104 HMAC implementation for php.
  572. //Creates an md5 HMAC.
  573. //Eliminates the need to install mhash to compute a HMAC
  574. //by Lance Rushing
  575. $bytelen = 64; //byte length for md5
  576. if (strlen($key) > $bytelen) {
  577. $key = pack('H*', md5($key));
  578. }
  579. $key = str_pad($key, $bytelen, chr(0x00));
  580. $ipad = str_pad('', $bytelen, chr(0x36));
  581. $opad = str_pad('', $bytelen, chr(0x5c));
  582. $k_ipad = $key ^ $ipad;
  583. $k_opad = $key ^ $opad;
  584. return md5($k_opad . pack('H*', md5($k_ipad . $data)));
  585. }
  586. /**
  587. * Check connection state.
  588. *
  589. * @return bool True if connected
  590. */
  591. public function connected()
  592. {
  593. if (is_resource($this->smtp_conn)) {
  594. $sock_status = stream_get_meta_data($this->smtp_conn);
  595. if ($sock_status['eof']) {
  596. //The socket is valid but we are not connected
  597. $this->edebug(
  598. 'SMTP NOTICE: EOF caught while checking if connected',
  599. self::DEBUG_CLIENT
  600. );
  601. $this->close();
  602. return false;
  603. }
  604. return true; //everything looks good
  605. }
  606. return false;
  607. }
  608. /**
  609. * Close the socket and clean up the state of the class.
  610. * Don't use this function without first trying to use QUIT.
  611. *
  612. * @see quit()
  613. */
  614. public function close()
  615. {
  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. * finalizing 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. //Don't clear the error store when using keepalive
  938. if ($command !== 'RSET') {
  939. $this->setError('');
  940. }
  941. return true;
  942. }
  943. /**
  944. * Send an SMTP SAML command.
  945. * Starts a mail transaction from the email address specified in $from.
  946. * Returns true if successful or false otherwise. If True
  947. * the mail transaction is started and then one or more recipient
  948. * commands may be called followed by a data command. This command
  949. * will send the message to the users terminal if they are logged
  950. * in and send them an email.
  951. * Implements RFC 821: SAML <SP> FROM:<reverse-path> <CRLF>.
  952. *
  953. * @param string $from The address the message is from
  954. *
  955. * @return bool
  956. */
  957. public function sendAndMail($from)
  958. {
  959. return $this->sendCommand('SAML', "SAML FROM:$from", 250);
  960. }
  961. /**
  962. * Send an SMTP VRFY command.
  963. *
  964. * @param string $name The name to verify
  965. *
  966. * @return bool
  967. */
  968. public function verify($name)
  969. {
  970. return $this->sendCommand('VRFY', "VRFY $name", [250, 251]);
  971. }
  972. /**
  973. * Send an SMTP NOOP command.
  974. * Used to keep keep-alives alive, doesn't actually do anything.
  975. *
  976. * @return bool
  977. */
  978. public function noop()
  979. {
  980. return $this->sendCommand('NOOP', 'NOOP', 250);
  981. }
  982. /**
  983. * Send an SMTP TURN command.
  984. * This is an optional command for SMTP that this class does not support.
  985. * This method is here to make the RFC821 Definition complete for this class
  986. * and _may_ be implemented in future.
  987. * Implements from RFC 821: TURN <CRLF>.
  988. *
  989. * @return bool
  990. */
  991. public function turn()
  992. {
  993. $this->setError('The SMTP TURN command is not implemented');
  994. $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
  995. return false;
  996. }
  997. /**
  998. * Send raw data to the server.
  999. *
  1000. * @param string $data The data to send
  1001. * @param string $command Optionally, the command this is part of, used only for controlling debug output
  1002. *
  1003. * @return int|bool The number of bytes sent to the server or false on error
  1004. */
  1005. public function client_send($data, $command = '')
  1006. {
  1007. //If SMTP transcripts are left enabled, or debug output is posted online
  1008. //it can leak credentials, so hide credentials in all but lowest level
  1009. if (
  1010. self::DEBUG_LOWLEVEL > $this->do_debug &&
  1011. in_array($command, ['User & Password', 'Username', 'Password'], true)
  1012. ) {
  1013. $this->edebug('CLIENT -> SERVER: [credentials hidden]', self::DEBUG_CLIENT);
  1014. } else {
  1015. $this->edebug('CLIENT -> SERVER: ' . $data, self::DEBUG_CLIENT);
  1016. }
  1017. set_error_handler([$this, 'errorHandler']);
  1018. $result = fwrite($this->smtp_conn, $data);
  1019. restore_error_handler();
  1020. return $result;
  1021. }
  1022. /**
  1023. * Get the latest error.
  1024. *
  1025. * @return array
  1026. */
  1027. public function getError()
  1028. {
  1029. return $this->error;
  1030. }
  1031. /**
  1032. * Get SMTP extensions available on the server.
  1033. *
  1034. * @return array|null
  1035. */
  1036. public function getServerExtList()
  1037. {
  1038. return $this->server_caps;
  1039. }
  1040. /**
  1041. * Get metadata about the SMTP server from its HELO/EHLO response.
  1042. * The method works in three ways, dependent on argument value and current state:
  1043. * 1. HELO/EHLO has not been sent - returns null and populates $this->error.
  1044. * 2. HELO has been sent -
  1045. * $name == 'HELO': returns server name
  1046. * $name == 'EHLO': returns boolean false
  1047. * $name == any other string: returns null and populates $this->error
  1048. * 3. EHLO has been sent -
  1049. * $name == 'HELO'|'EHLO': returns the server name
  1050. * $name == any other string: if extension $name exists, returns True
  1051. * or its options (e.g. AUTH mechanisms supported). Otherwise returns False.
  1052. *
  1053. * @param string $name Name of SMTP extension or 'HELO'|'EHLO'
  1054. *
  1055. * @return string|bool|null
  1056. */
  1057. public function getServerExt($name)
  1058. {
  1059. if (!$this->server_caps) {
  1060. $this->setError('No HELO/EHLO was sent');
  1061. return null;
  1062. }
  1063. if (!array_key_exists($name, $this->server_caps)) {
  1064. if ('HELO' === $name) {
  1065. return $this->server_caps['EHLO'];
  1066. }
  1067. if ('EHLO' === $name || array_key_exists('EHLO', $this->server_caps)) {
  1068. return false;
  1069. }
  1070. $this->setError('HELO handshake was used; No information about server extensions available');
  1071. return null;
  1072. }
  1073. return $this->server_caps[$name];
  1074. }
  1075. /**
  1076. * Get the last reply from the server.
  1077. *
  1078. * @return string
  1079. */
  1080. public function getLastReply()
  1081. {
  1082. return $this->last_reply;
  1083. }
  1084. /**
  1085. * Read the SMTP server's response.
  1086. * Either before eof or socket timeout occurs on the operation.
  1087. * With SMTP we can tell if we have more lines to read if the
  1088. * 4th character is '-' symbol. If it is a space then we don't
  1089. * need to read anything else.
  1090. *
  1091. * @return string
  1092. */
  1093. protected function get_lines()
  1094. {
  1095. //If the connection is bad, give up straight away
  1096. if (!is_resource($this->smtp_conn)) {
  1097. return '';
  1098. }
  1099. $data = '';
  1100. $endtime = 0;
  1101. stream_set_timeout($this->smtp_conn, $this->Timeout);
  1102. if ($this->Timelimit > 0) {
  1103. $endtime = time() + $this->Timelimit;
  1104. }
  1105. $selR = [$this->smtp_conn];
  1106. $selW = null;
  1107. while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
  1108. //Must pass vars in here as params are by reference
  1109. //solution for signals inspired by https://github.com/symfony/symfony/pull/6540
  1110. set_error_handler([$this, 'errorHandler']);
  1111. $n = stream_select($selR, $selW, $selW, $this->Timelimit);
  1112. restore_error_handler();
  1113. if ($n === false) {
  1114. $message = $this->getError()['detail'];
  1115. $this->edebug(
  1116. 'SMTP -> get_lines(): select failed (' . $message . ')',
  1117. self::DEBUG_LOWLEVEL
  1118. );
  1119. //stream_select returns false when the `select` system call is interrupted
  1120. //by an incoming signal, try the select again
  1121. if (stripos($message, 'interrupted system call') !== false) {
  1122. $this->edebug(
  1123. 'SMTP -> get_lines(): retrying stream_select',
  1124. self::DEBUG_LOWLEVEL
  1125. );
  1126. $this->setError('');
  1127. continue;
  1128. }
  1129. break;
  1130. }
  1131. if (!$n) {
  1132. $this->edebug(
  1133. 'SMTP -> get_lines(): select timed-out in (' . $this->Timelimit . ' sec)',
  1134. self::DEBUG_LOWLEVEL
  1135. );
  1136. break;
  1137. }
  1138. //Deliberate noise suppression - errors are handled afterwards
  1139. $str = @fgets($this->smtp_conn, self::MAX_REPLY_LENGTH);
  1140. $this->edebug('SMTP INBOUND: "' . trim($str) . '"', self::DEBUG_LOWLEVEL);
  1141. $data .= $str;
  1142. //If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled),
  1143. //or 4th character is a space or a line break char, we are done reading, break the loop.
  1144. //String array access is a significant micro-optimisation over strlen
  1145. if (!isset($str[3]) || $str[3] === ' ' || $str[3] === "\r" || $str[3] === "\n") {
  1146. break;
  1147. }
  1148. //Timed-out? Log and break
  1149. $info = stream_get_meta_data($this->smtp_conn);
  1150. if ($info['timed_out']) {
  1151. $this->edebug(
  1152. 'SMTP -> get_lines(): stream timed-out (' . $this->Timeout . ' sec)',
  1153. self::DEBUG_LOWLEVEL
  1154. );
  1155. break;
  1156. }
  1157. //Now check if reads took too long
  1158. if ($endtime && time() > $endtime) {
  1159. $this->edebug(
  1160. 'SMTP -> get_lines(): timelimit reached (' .
  1161. $this->Timelimit . ' sec)',
  1162. self::DEBUG_LOWLEVEL
  1163. );
  1164. break;
  1165. }
  1166. }
  1167. return $data;
  1168. }
  1169. /**
  1170. * Enable or disable VERP address generation.
  1171. *
  1172. * @param bool $enabled
  1173. */
  1174. public function setVerp($enabled = false)
  1175. {
  1176. $this->do_verp = $enabled;
  1177. }
  1178. /**
  1179. * Get VERP address generation mode.
  1180. *
  1181. * @return bool
  1182. */
  1183. public function getVerp()
  1184. {
  1185. return $this->do_verp;
  1186. }
  1187. /**
  1188. * Set error messages and codes.
  1189. *
  1190. * @param string $message The error message
  1191. * @param string $detail Further detail on the error
  1192. * @param string $smtp_code An associated SMTP error code
  1193. * @param string $smtp_code_ex Extended SMTP code
  1194. */
  1195. protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
  1196. {
  1197. $this->error = [
  1198. 'error' => $message,
  1199. 'detail' => $detail,
  1200. 'smtp_code' => $smtp_code,
  1201. 'smtp_code_ex' => $smtp_code_ex,
  1202. ];
  1203. }
  1204. /**
  1205. * Set debug output method.
  1206. *
  1207. * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it
  1208. */
  1209. public function setDebugOutput($method = 'echo')
  1210. {
  1211. $this->Debugoutput = $method;
  1212. }
  1213. /**
  1214. * Get debug output method.
  1215. *
  1216. * @return string
  1217. */
  1218. public function getDebugOutput()
  1219. {
  1220. return $this->Debugoutput;
  1221. }
  1222. /**
  1223. * Set debug output level.
  1224. *
  1225. * @param int $level
  1226. */
  1227. public function setDebugLevel($level = 0)
  1228. {
  1229. $this->do_debug = $level;
  1230. }
  1231. /**
  1232. * Get debug output level.
  1233. *
  1234. * @return int
  1235. */
  1236. public function getDebugLevel()
  1237. {
  1238. return $this->do_debug;
  1239. }
  1240. /**
  1241. * Set SMTP timeout.
  1242. *
  1243. * @param int $timeout The timeout duration in seconds
  1244. */
  1245. public function setTimeout($timeout = 0)
  1246. {
  1247. $this->Timeout = $timeout;
  1248. }
  1249. /**
  1250. * Get SMTP timeout.
  1251. *
  1252. * @return int
  1253. */
  1254. public function getTimeout()
  1255. {
  1256. return $this->Timeout;
  1257. }
  1258. /**
  1259. * Reports an error number and string.
  1260. *
  1261. * @param int $errno The error number returned by PHP
  1262. * @param string $errmsg The error message returned by PHP
  1263. * @param string $errfile The file the error occurred in
  1264. * @param int $errline The line number the error occurred on
  1265. */
  1266. protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0)
  1267. {
  1268. $notice = 'Connection failed.';
  1269. $this->setError(
  1270. $notice,
  1271. $errmsg,
  1272. (string) $errno
  1273. );
  1274. $this->edebug(
  1275. "$notice Error #$errno: $errmsg [$errfile line $errline]",
  1276. self::DEBUG_CONNECTION
  1277. );
  1278. }
  1279. /**
  1280. * Extract and return the ID of the last SMTP transaction based on
  1281. * a list of patterns provided in SMTP::$smtp_transaction_id_patterns.
  1282. * Relies on the host providing the ID in response to a DATA command.
  1283. * If no reply has been received yet, it will return null.
  1284. * If no pattern was matched, it will return false.
  1285. *
  1286. * @return bool|string|null
  1287. */
  1288. protected function recordLastTransactionID()
  1289. {
  1290. $reply = $this->getLastReply();
  1291. if (empty($reply)) {
  1292. $this->last_smtp_transaction_id = null;
  1293. } else {
  1294. $this->last_smtp_transaction_id = false;
  1295. foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
  1296. $matches = [];
  1297. if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
  1298. $this->last_smtp_transaction_id = trim($matches[1]);
  1299. break;
  1300. }
  1301. }
  1302. }
  1303. return $this->last_smtp_transaction_id;
  1304. }
  1305. /**
  1306. * Get the queue/transaction ID of the last SMTP transaction
  1307. * If no reply has been received yet, it will return null.
  1308. * If no pattern was matched, it will return false.
  1309. *
  1310. * @return bool|string|null
  1311. *
  1312. * @see recordLastTransactionID()
  1313. */
  1314. public function getLastTransactionID()
  1315. {
  1316. return $this->last_smtp_transaction_id;
  1317. }
  1318. }