You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1187 lines
39 KiB

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