説明なし

SMTP.php 42KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  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 App\Libs\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.5';
  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 (bool) ($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. }