Няма описание

SMTP.php 46KB

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