SMTP.php 46 KB

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