class.smtp.php 39 KB

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