PageRenderTime 29ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/Envio Mails Android -PHP/SendEmailPHP/class.smtp.php

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