SMTP.php 43 KB

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