Git for the orangehattech website https://orangehattech.com
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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