*/}}

SMTP.php 48 KB

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