SMTP.php 39 KB

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