SMTP.php 37 KB

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