SMTP.php 35 KB

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