PageRenderTime 62ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/core/lib/phpmailer/class.smtp.php

http://github.com/nshahzad/phpVMS
PHP | 1249 lines | 649 code | 93 blank | 507 comment | 82 complexity | 39c36c3b509244afec319c1b89ac4d63 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, MIT
  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, NTLM, CRAM-MD5, XOAUTH2)
  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', 'NTLM', 'XOAUTH2') 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 'XOAUTH2':
  431. //If the OAuth Instance is not set. Can be a case when PHPMailer is used
  432. //instead of PHPMailerOAuth
  433. if (is_null($OAuth)) {
  434. return false;
  435. }
  436. $oauth = $OAuth->getOauth64();
  437. // Start authentication
  438. if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
  439. return false;
  440. }
  441. break;
  442. case 'NTLM':
  443. /*
  444. * ntlm_sasl_client.php
  445. * Bundled with Permission
  446. *
  447. * How to telnet in windows:
  448. * http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
  449. * PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
  450. */
  451. require_once 'extras/ntlm_sasl_client.php';
  452. $temp = new stdClass;
  453. $ntlm_client = new ntlm_sasl_client_class;
  454. //Check that functions are available
  455. if (!$ntlm_client->initialize($temp)) {
  456. $this->setError($temp->error);
  457. $this->edebug(
  458. 'You need to enable some modules in your php.ini file: '
  459. . $this->error['error'],
  460. self::DEBUG_CLIENT
  461. );
  462. return false;
  463. }
  464. //msg1
  465. $msg1 = $ntlm_client->typeMsg1($realm, $workstation); //msg1
  466. if (!$this->sendCommand(
  467. 'AUTH NTLM',
  468. 'AUTH NTLM ' . base64_encode($msg1),
  469. 334
  470. )
  471. ) {
  472. return false;
  473. }
  474. //Though 0 based, there is a white space after the 3 digit number
  475. //msg2
  476. $challenge = substr($this->last_reply, 3);
  477. $challenge = base64_decode($challenge);
  478. $ntlm_res = $ntlm_client->NTLMResponse(
  479. substr($challenge, 24, 8),
  480. $password
  481. );
  482. //msg3
  483. $msg3 = $ntlm_client->typeMsg3(
  484. $ntlm_res,
  485. $username,
  486. $realm,
  487. $workstation
  488. );
  489. // send encoded username
  490. return $this->sendCommand('Username', base64_encode($msg3), 235);
  491. case 'CRAM-MD5':
  492. // Start authentication
  493. if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
  494. return false;
  495. }
  496. // Get the challenge
  497. $challenge = base64_decode(substr($this->last_reply, 4));
  498. // Build the response
  499. $response = $username . ' ' . $this->hmac($challenge, $password);
  500. // send encoded credentials
  501. return $this->sendCommand('Username', base64_encode($response), 235);
  502. default:
  503. $this->setError("Authentication method \"$authtype\" is not supported");
  504. return false;
  505. }
  506. return true;
  507. }
  508. /**
  509. * Calculate an MD5 HMAC hash.
  510. * Works like hash_hmac('md5', $data, $key)
  511. * in case that function is not available
  512. * @param string $data The data to hash
  513. * @param string $key The key to hash with
  514. * @access protected
  515. * @return string
  516. */
  517. protected function hmac($data, $key)
  518. {
  519. if (function_exists('hash_hmac')) {
  520. return hash_hmac('md5', $data, $key);
  521. }
  522. // The following borrowed from
  523. // http://php.net/manual/en/function.mhash.php#27225
  524. // RFC 2104 HMAC implementation for php.
  525. // Creates an md5 HMAC.
  526. // Eliminates the need to install mhash to compute a HMAC
  527. // by Lance Rushing
  528. $bytelen = 64; // byte length for md5
  529. if (strlen($key) > $bytelen) {
  530. $key = pack('H*', md5($key));
  531. }
  532. $key = str_pad($key, $bytelen, chr(0x00));
  533. $ipad = str_pad('', $bytelen, chr(0x36));
  534. $opad = str_pad('', $bytelen, chr(0x5c));
  535. $k_ipad = $key ^ $ipad;
  536. $k_opad = $key ^ $opad;
  537. return md5($k_opad . pack('H*', md5($k_ipad . $data)));
  538. }
  539. /**
  540. * Check connection state.
  541. * @access public
  542. * @return boolean True if connected.
  543. */
  544. public function connected()
  545. {
  546. if (is_resource($this->smtp_conn)) {
  547. $sock_status = stream_get_meta_data($this->smtp_conn);
  548. if ($sock_status['eof']) {
  549. // The socket is valid but we are not connected
  550. $this->edebug(
  551. 'SMTP NOTICE: EOF caught while checking if connected',
  552. self::DEBUG_CLIENT
  553. );
  554. $this->close();
  555. return false;
  556. }
  557. return true; // everything looks good
  558. }
  559. return false;
  560. }
  561. /**
  562. * Close the socket and clean up the state of the class.
  563. * Don't use this function without first trying to use QUIT.
  564. * @see quit()
  565. * @access public
  566. * @return void
  567. */
  568. public function close()
  569. {
  570. $this->setError('');
  571. $this->server_caps = null;
  572. $this->helo_rply = null;
  573. if (is_resource($this->smtp_conn)) {
  574. // close the connection and cleanup
  575. fclose($this->smtp_conn);
  576. $this->smtp_conn = null; //Makes for cleaner serialization
  577. $this->edebug('Connection: closed', self::DEBUG_CONNECTION);
  578. }
  579. }
  580. /**
  581. * Send an SMTP DATA command.
  582. * Issues a data command and sends the msg_data to the server,
  583. * finializing the mail transaction. $msg_data is the message
  584. * that is to be send with the headers. Each header needs to be
  585. * on a single line followed by a <CRLF> with the message headers
  586. * and the message body being separated by and additional <CRLF>.
  587. * Implements rfc 821: DATA <CRLF>
  588. * @param string $msg_data Message data to send
  589. * @access public
  590. * @return boolean
  591. */
  592. public function data($msg_data)
  593. {
  594. //This will use the standard timelimit
  595. if (!$this->sendCommand('DATA', 'DATA', 354)) {
  596. return false;
  597. }
  598. /* The server is ready to accept data!
  599. * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF)
  600. * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
  601. * smaller lines to fit within the limit.
  602. * We will also look for lines that start with a '.' and prepend an additional '.'.
  603. * NOTE: this does not count towards line-length limit.
  604. */
  605. // Normalize line breaks before exploding
  606. $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
  607. /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
  608. * of the first line (':' separated) does not contain a space then it _should_ be a header and we will
  609. * process all lines before a blank line as headers.
  610. */
  611. $field = substr($lines[0], 0, strpos($lines[0], ':'));
  612. $in_headers = false;
  613. if (!empty($field) && strpos($field, ' ') === false) {
  614. $in_headers = true;
  615. }
  616. foreach ($lines as $line) {
  617. $lines_out = array();
  618. if ($in_headers and $line == '') {
  619. $in_headers = false;
  620. }
  621. //Break this line up into several smaller lines if it's too long
  622. //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
  623. while (isset($line[self::MAX_LINE_LENGTH])) {
  624. //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
  625. //so as to avoid breaking in the middle of a word
  626. $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
  627. //Deliberately matches both false and 0
  628. if (!$pos) {
  629. //No nice break found, add a hard break
  630. $pos = self::MAX_LINE_LENGTH - 1;
  631. $lines_out[] = substr($line, 0, $pos);
  632. $line = substr($line, $pos);
  633. } else {
  634. //Break at the found point
  635. $lines_out[] = substr($line, 0, $pos);
  636. //Move along by the amount we dealt with
  637. $line = substr($line, $pos + 1);
  638. }
  639. //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
  640. if ($in_headers) {
  641. $line = "\t" . $line;
  642. }
  643. }
  644. $lines_out[] = $line;
  645. //Send the lines to the server
  646. foreach ($lines_out as $line_out) {
  647. //RFC2821 section 4.5.2
  648. if (!empty($line_out) and $line_out[0] == '.') {
  649. $line_out = '.' . $line_out;
  650. }
  651. $this->client_send($line_out . self::CRLF);
  652. }
  653. }
  654. //Message data has been sent, complete the command
  655. //Increase timelimit for end of DATA command
  656. $savetimelimit = $this->Timelimit;
  657. $this->Timelimit = $this->Timelimit * 2;
  658. $result = $this->sendCommand('DATA END', '.', 250);
  659. //Restore timelimit
  660. $this->Timelimit = $savetimelimit;
  661. return $result;
  662. }
  663. /**
  664. * Send an SMTP HELO or EHLO command.
  665. * Used to identify the sending server to the receiving server.
  666. * This makes sure that client and server are in a known state.
  667. * Implements RFC 821: HELO <SP> <domain> <CRLF>
  668. * and RFC 2821 EHLO.
  669. * @param string $host The host name or IP to connect to
  670. * @access public
  671. * @return boolean
  672. */
  673. public function hello($host = '')
  674. {
  675. //Try extended hello first (RFC 2821)
  676. return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
  677. }
  678. /**
  679. * Send an SMTP HELO or EHLO command.
  680. * Low-level implementation used by hello()
  681. * @see hello()
  682. * @param string $hello The HELO string
  683. * @param string $host The hostname to say we are
  684. * @access protected
  685. * @return boolean
  686. */
  687. protected function sendHello($hello, $host)
  688. {
  689. $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
  690. $this->helo_rply = $this->last_reply;
  691. if ($noerror) {
  692. $this->parseHelloFields($hello);
  693. } else {
  694. $this->server_caps = null;
  695. }
  696. return $noerror;
  697. }
  698. /**
  699. * Parse a reply to HELO/EHLO command to discover server extensions.
  700. * In case of HELO, the only parameter that can be discovered is a server name.
  701. * @access protected
  702. * @param string $type - 'HELO' or 'EHLO'
  703. */
  704. protected function parseHelloFields($type)
  705. {
  706. $this->server_caps = array();
  707. $lines = explode("\n", $this->helo_rply);
  708. foreach ($lines as $n => $s) {
  709. //First 4 chars contain response code followed by - or space
  710. $s = trim(substr($s, 4));
  711. if (empty($s)) {
  712. continue;
  713. }
  714. $fields = explode(' ', $s);
  715. if (!empty($fields)) {
  716. if (!$n) {
  717. $name = $type;
  718. $fields = $fields[0];
  719. } else {
  720. $name = array_shift($fields);
  721. switch ($name) {
  722. case 'SIZE':
  723. $fields = ($fields ? $fields[0] : 0);
  724. break;
  725. case 'AUTH':
  726. if (!is_array($fields)) {
  727. $fields = array();
  728. }
  729. break;
  730. default:
  731. $fields = true;
  732. }
  733. }
  734. $this->server_caps[$name] = $fields;
  735. }
  736. }
  737. }
  738. /**
  739. * Send an SMTP MAIL command.
  740. * Starts a mail transaction from the email address specified in
  741. * $from. Returns true if successful or false otherwise. If True
  742. * the mail transaction is started and then one or more recipient
  743. * commands may be called followed by a data command.
  744. * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
  745. * @param string $from Source address of this message
  746. * @access public
  747. * @return boolean
  748. */
  749. public function mail($from)
  750. {
  751. $useVerp = ($this->do_verp ? ' XVERP' : '');
  752. return $this->sendCommand(
  753. 'MAIL FROM',
  754. 'MAIL FROM:<' . $from . '>' . $useVerp,
  755. 250
  756. );
  757. }
  758. /**
  759. * Send an SMTP QUIT command.
  760. * Closes the socket if there is no error or the $close_on_error argument is true.
  761. * Implements from rfc 821: QUIT <CRLF>
  762. * @param boolean $close_on_error Should the connection close if an error occurs?
  763. * @access public
  764. * @return boolean
  765. */
  766. public function quit($close_on_error = true)
  767. {
  768. $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
  769. $err = $this->error; //Save any error
  770. if ($noerror or $close_on_error) {
  771. $this->close();
  772. $this->error = $err; //Restore any error from the quit command
  773. }
  774. return $noerror;
  775. }
  776. /**
  777. * Send an SMTP RCPT command.
  778. * Sets the TO argument to $toaddr.
  779. * Returns true if the recipient was accepted false if it was rejected.
  780. * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
  781. * @param string $address The address the message is being sent to
  782. * @access public
  783. * @return boolean
  784. */
  785. public function recipient($address)
  786. {
  787. return $this->sendCommand(
  788. 'RCPT TO',
  789. 'RCPT TO:<' . $address . '>',
  790. array(250, 251)
  791. );
  792. }
  793. /**
  794. * Send an SMTP RSET command.
  795. * Abort any transaction that is currently in progress.
  796. * Implements rfc 821: RSET <CRLF>
  797. * @access public
  798. * @return boolean True on success.
  799. */
  800. public function reset()
  801. {
  802. return $this->sendCommand('RSET', 'RSET', 250);
  803. }
  804. /**
  805. * Send a command to an SMTP server and check its return code.
  806. * @param string $command The command name - not sent to the server
  807. * @param string $commandstring The actual command to send
  808. * @param integer|array $expect One or more expected integer success codes
  809. * @access protected
  810. * @return boolean True on success.
  811. */
  812. protected function sendCommand($command, $commandstring, $expect)
  813. {
  814. if (!$this->connected()) {
  815. $this->setError("Called $command without being connected");
  816. return false;
  817. }
  818. //Reject line breaks in all commands
  819. if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) {
  820. $this->setError("Command '$command' contained line breaks");
  821. return false;
  822. }
  823. $this->client_send($commandstring . self::CRLF);
  824. $this->last_reply = $this->get_lines();
  825. // Fetch SMTP code and possible error code explanation
  826. $matches = array();
  827. if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) {
  828. $code = $matches[1];
  829. $code_ex = (count($matches) > 2 ? $matches[2] : null);
  830. // Cut off error code from each response line
  831. $detail = preg_replace(
  832. "/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m",
  833. '',
  834. $this->last_reply
  835. );
  836. } else {
  837. // Fall back to simple parsing if regex fails
  838. $code = substr($this->last_reply, 0, 3);
  839. $code_ex = null;
  840. $detail = substr($this->last_reply, 4);
  841. }
  842. $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
  843. if (!in_array($code, (array)$expect)) {
  844. $this->setError(
  845. "$command command failed",
  846. $detail,
  847. $code,
  848. $code_ex
  849. );
  850. $this->edebug(
  851. 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,
  852. self::DEBUG_CLIENT
  853. );
  854. return false;
  855. }
  856. $this->setError('');
  857. return true;
  858. }
  859. /**
  860. * Send an SMTP SAML command.
  861. * Starts a mail transaction from the email address specified in $from.
  862. * Returns true if successful or false otherwise. If True
  863. * the mail transaction is started and then one or more recipient
  864. * commands may be called followed by a data command. This command
  865. * will send the message to the users terminal if they are logged
  866. * in and send them an email.
  867. * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
  868. * @param string $from The address the message is from
  869. * @access public
  870. * @return boolean
  871. */
  872. public function sendAndMail($from)
  873. {
  874. return $this->sendCommand('SAML', "SAML FROM:$from", 250);
  875. }
  876. /**
  877. * Send an SMTP VRFY command.
  878. * @param string $name The name to verify
  879. * @access public
  880. * @return boolean
  881. */
  882. public function verify($name)
  883. {
  884. return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
  885. }
  886. /**
  887. * Send an SMTP NOOP command.
  888. * Used to keep keep-alives alive, doesn't actually do anything
  889. * @access public
  890. * @return boolean
  891. */
  892. public function noop()
  893. {
  894. return $this->sendCommand('NOOP', 'NOOP', 250);
  895. }
  896. /**
  897. * Send an SMTP TURN command.
  898. * This is an optional command for SMTP that this class does not support.
  899. * This method is here to make the RFC821 Definition complete for this class
  900. * and _may_ be implemented in future
  901. * Implements from rfc 821: TURN <CRLF>
  902. * @access public
  903. * @return boolean
  904. */
  905. public function turn()
  906. {
  907. $this->setError('The SMTP TURN command is not implemented');
  908. $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
  909. return false;
  910. }
  911. /**
  912. * Send raw data to the server.
  913. * @param string $data The data to send
  914. * @access public
  915. * @return integer|boolean The number of bytes sent to the server or false on error
  916. */
  917. public function client_send($data)
  918. {
  919. $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT);
  920. return fwrite($this->smtp_conn, $data);
  921. }
  922. /**
  923. * Get the latest error.
  924. * @access public
  925. * @return array
  926. */
  927. public function getError()
  928. {
  929. return $this->error;
  930. }
  931. /**
  932. * Get SMTP extensions available on the server
  933. * @access public
  934. * @return array|null
  935. */
  936. public function getServerExtList()
  937. {
  938. return $this->server_caps;
  939. }
  940. /**
  941. * A multipurpose method
  942. * The method works in three ways, dependent on argument value and current state
  943. * 1. HELO/EHLO was not sent - returns null and set up $this->error
  944. * 2. HELO was sent
  945. * $name = 'HELO': returns server name
  946. * $name = 'EHLO': returns boolean false
  947. * $name = any string: returns null and set up $this->error
  948. * 3. EHLO was sent
  949. * $name = 'HELO'|'EHLO': returns server name
  950. * $name = any string: if extension $name exists, returns boolean True
  951. * or its options. Otherwise returns boolean False
  952. * In other words, one can use this method to detect 3 conditions:
  953. * - null returned: handshake was not or we don't know about ext (refer to $this->error)
  954. * - false returned: the requested feature exactly not exists
  955. * - positive value returned: the requested feature exists
  956. * @param string $name Name of SMTP extension or 'HELO'|'EHLO'
  957. * @return mixed
  958. */
  959. public function getServerExt($name)
  960. {
  961. if (!$this->server_caps) {
  962. $this->setError('No HELO/EHLO was sent');
  963. return null;
  964. }
  965. // the tight logic knot ;)
  966. if (!array_key_exists($name, $this->server_caps)) {
  967. if ($name == 'HELO') {
  968. return $this->server_caps['EHLO'];
  969. }
  970. if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) {
  971. return false;
  972. }
  973. $this->setError('HELO handshake was used. Client knows nothing about server extensions');
  974. return null;
  975. }
  976. return $this->server_caps[$name];
  977. }
  978. /**
  979. * Get the last reply from the server.
  980. * @access public
  981. * @return string
  982. */
  983. public function getLastReply()
  984. {
  985. return $this->last_reply;
  986. }
  987. /**
  988. * Read the SMTP server's response.
  989. * Either before eof or socket timeout occurs on the operation.
  990. * With SMTP we can tell if we have more lines to read if the
  991. * 4th character is '-' symbol. If it is a space then we don't
  992. * need to read anything else.
  993. * @access protected
  994. * @return string
  995. */
  996. protected function get_lines()
  997. {
  998. // If the connection is bad, give up straight away
  999. if (!is_resource($this->smtp_conn)) {
  1000. return '';
  1001. }
  1002. $data = '';
  1003. $endtime = 0;
  1004. stream_set_timeout($this->smtp_conn, $this->Timeout);
  1005. if ($this->Timelimit > 0) {
  1006. $endtime = time() + $this->Timelimit;
  1007. }
  1008. while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
  1009. $str = @fgets($this->smtp_conn, 515);
  1010. $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL);
  1011. $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL);
  1012. $data .= $str;
  1013. // If 4th character is a space, we are done reading, break the loop, micro-optimisation over strlen
  1014. if ((isset($str[3]) and $str[3] == ' ')) {
  1015. break;
  1016. }
  1017. // Timed-out? Log and break
  1018. $info = stream_get_meta_data($this->smtp_conn);
  1019. if ($info['timed_out']) {
  1020. $this->edebug(
  1021. 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
  1022. self::DEBUG_LOWLEVEL
  1023. );
  1024. break;
  1025. }
  1026. // Now check if reads took too long
  1027. if ($endtime and time() > $endtime) {
  1028. $this->edebug(
  1029. 'SMTP -> get_lines(): timelimit reached ('.
  1030. $this->Timelimit . ' sec)',
  1031. self::DEBUG_LOWLEVEL
  1032. );
  1033. break;
  1034. }
  1035. }
  1036. return $data;
  1037. }
  1038. /**
  1039. * Enable or disable VERP address generation.
  1040. * @param boolean $enabled
  1041. */
  1042. public function setVerp($enabled = false)
  1043. {
  1044. $this->do_verp = $enabled;
  1045. }
  1046. /**
  1047. * Get VERP address generation mode.
  1048. * @return boolean
  1049. */
  1050. public function getVerp()
  1051. {
  1052. return $this->do_verp;
  1053. }
  1054. /**
  1055. * Set error messages and codes.
  1056. * @param string $message The error message
  1057. * @param string $detail Further detail on the error
  1058. * @param string $smtp_code An associated SMTP error code
  1059. * @param string $smtp_code_ex Extended SMTP code
  1060. */
  1061. protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
  1062. {
  1063. $this->error = array(
  1064. 'error' => $message,
  1065. 'detail' => $detail,
  1066. 'smtp_code' => $smtp_code,
  1067. 'smtp_code_ex' => $smtp_code_ex
  1068. );
  1069. }
  1070. /**
  1071. * Set debug output method.
  1072. * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it.
  1073. */
  1074. public function setDebugOutput($method = 'echo')
  1075. {
  1076. $this->Debugoutput = $method;
  1077. }
  1078. /**
  1079. * Get debug output method.
  1080. * @return string
  1081. */
  1082. public function getDebugOutput()
  1083. {
  1084. return $this->Debugoutput;
  1085. }
  1086. /**
  1087. * Set debug output level.
  1088. * @param integer $level
  1089. */
  1090. public function setDebugLevel($level = 0)
  1091. {
  1092. $this->do_debug = $level;
  1093. }
  1094. /**
  1095. * Get debug output level.
  1096. * @return integer
  1097. */
  1098. public function getDebugLevel()
  1099. {
  1100. return $this->do_debug;
  1101. }
  1102. /**
  1103. * Set SMTP timeout.
  1104. * @param integer $timeout
  1105. */
  1106. public function setTimeout($timeout = 0)
  1107. {
  1108. $this->Timeout = $timeout;
  1109. }
  1110. /**
  1111. * Get SMTP timeout.
  1112. * @return integer
  1113. */
  1114. public function getTimeout()
  1115. {
  1116. return $this->Timeout;
  1117. }
  1118. /**
  1119. * Reports an error number and string.
  1120. * @param integer $errno The error number returned by PHP.
  1121. * @param string $errmsg The error message returned by PHP.
  1122. */
  1123. protected function errorHandler($errno, $errmsg)
  1124. {
  1125. $notice = 'Connection: Failed to connect to server.';
  1126. $this->setError(
  1127. $notice,
  1128. $errno,
  1129. $errmsg
  1130. );
  1131. $this->edebug(
  1132. $notice . ' Error number ' . $errno . '. "Error notice: ' . $errmsg,
  1133. self::DEBUG_CONNECTION
  1134. );
  1135. }
  1136. /**
  1137. * Will return the ID of the last smtp transaction based on a list of patterns provided
  1138. * in SMTP::$smtp_transaction_id_patterns.
  1139. * If no reply has been received yet, it will return null.
  1140. * If no pattern has been matched, it will return false.
  1141. * @return bool|null|string
  1142. */
  1143. public function getLastTransactionID()
  1144. {
  1145. $reply = $this->getLastReply();
  1146. if (empty($reply)) {
  1147. return null;
  1148. }
  1149. foreach($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
  1150. if(preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
  1151. return $matches[1];
  1152. }
  1153. }
  1154. return false;
  1155. }
  1156. }