SMTP.php

File

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

Classes

Namesort descending Description
SMTP PHPMailer RFC821 SMTP email transport class. Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.