class.smtp.php 39 KB

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