SMTP.php 47 KB

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