Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

SMTP.php 42KB

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