<?php1/**2* PHPMailer RFC821 SMTP email transport class.3* PHP Version 5.5.4*5* @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project6*7* @author Marcus Bointon (Synchro/coolbru) <[email protected]>8* @author Jim Jagielski (jimjag) <[email protected]>9* @author Andy Prevost (codeworxtech) <[email protected]>10* @author Brent R. Matzelle (original founder)11* @copyright 2012 - 2020 Marcus Bointon12* @copyright 2010 - 2012 Jim Jagielski13* @copyright 2004 - 2009 Andy Prevost14* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License15* @note This program is distributed in the hope that it will be useful - WITHOUT16* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or17* FITNESS FOR A PARTICULAR PURPOSE.18*/1920namespace PHPMailer\PHPMailer;2122/**23* PHPMailer RFC821 SMTP email transport class.24* Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.25*26* @author Chris Ryan27* @author Marcus Bointon <[email protected]>28*/29class SMTP30{31/**32* The PHPMailer SMTP version number.33*34* @var string35*/36const VERSION = '6.1.7';3738/**39* SMTP line break constant.40*41* @var string42*/43const LE = "\r\n";4445/**46* The SMTP port to use if one is not specified.47*48* @var int49*/50const DEFAULT_PORT = 25;5152/**53* The maximum line length allowed by RFC 5321 section 4.5.3.1.6,54* *excluding* a trailing CRLF break.55*56* @see https://tools.ietf.org/html/rfc5321#section-4.5.3.1.657*58* @var int59*/60const MAX_LINE_LENGTH = 998;6162/**63* The maximum line length allowed for replies in RFC 5321 section 4.5.3.1.5,64* *including* a trailing CRLF line break.65*66* @see https://tools.ietf.org/html/rfc5321#section-4.5.3.1.567*68* @var int69*/70const MAX_REPLY_LENGTH = 512;7172/**73* Debug level for no output.74*75* @var int76*/77const DEBUG_OFF = 0;7879/**80* Debug level to show client -> server messages.81*82* @var int83*/84const DEBUG_CLIENT = 1;8586/**87* Debug level to show client -> server and server -> client messages.88*89* @var int90*/91const DEBUG_SERVER = 2;9293/**94* Debug level to show connection status, client -> server and server -> client messages.95*96* @var int97*/98const DEBUG_CONNECTION = 3;99100/**101* Debug level to show all messages.102*103* @var int104*/105const DEBUG_LOWLEVEL = 4;106107/**108* Debug output level.109* Options:110* * self::DEBUG_OFF (`0`) No debug output, default111* * self::DEBUG_CLIENT (`1`) Client commands112* * self::DEBUG_SERVER (`2`) Client commands and server responses113* * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status114* * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages.115*116* @var int117*/118public $do_debug = self::DEBUG_OFF;119120/**121* How to handle debug output.122* Options:123* * `echo` Output plain-text as-is, appropriate for CLI124* * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output125* * `error_log` Output to error log as configured in php.ini126* Alternatively, you can provide a callable expecting two params: a message string and the debug level:127*128* ```php129* $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};130* ```131*132* Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`133* level output is used:134*135* ```php136* $mail->Debugoutput = new myPsr3Logger;137* ```138*139* @var string|callable|\Psr\Log\LoggerInterface140*/141public $Debugoutput = 'echo';142143/**144* Whether to use VERP.145*146* @see http://en.wikipedia.org/wiki/Variable_envelope_return_path147* @see http://www.postfix.org/VERP_README.html Info on VERP148*149* @var bool150*/151public $do_verp = false;152153/**154* The timeout value for connection, in seconds.155* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.156* This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.157*158* @see http://tools.ietf.org/html/rfc2821#section-4.5.3.2159*160* @var int161*/162public $Timeout = 300;163164/**165* How long to wait for commands to complete, in seconds.166* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.167*168* @var int169*/170public $Timelimit = 300;171172/**173* Patterns to extract an SMTP transaction id from reply to a DATA command.174* The first capture group in each regex will be used as the ID.175* MS ESMTP returns the message ID, which may not be correct for internal tracking.176*177* @var string[]178*/179protected $smtp_transaction_id_patterns = [180'exim' => '/[\d]{3} OK id=(.*)/',181'sendmail' => '/[\d]{3} 2.0.0 (.*) Message/',182'postfix' => '/[\d]{3} 2.0.0 Ok: queued as (.*)/',183'Microsoft_ESMTP' => '/[0-9]{3} 2.[\d].0 (.*)@(?:.*) Queued mail for delivery/',184'Amazon_SES' => '/[\d]{3} Ok (.*)/',185'SendGrid' => '/[\d]{3} Ok: queued as (.*)/',186'CampaignMonitor' => '/[\d]{3} 2.0.0 OK:([a-zA-Z\d]{48})/',187];188189/**190* The last transaction ID issued in response to a DATA command,191* if one was detected.192*193* @var string|bool|null194*/195protected $last_smtp_transaction_id;196197/**198* The socket for the server connection.199*200* @var ?resource201*/202protected $smtp_conn;203204/**205* Error information, if any, for the last SMTP command.206*207* @var array208*/209protected $error = [210'error' => '',211'detail' => '',212'smtp_code' => '',213'smtp_code_ex' => '',214];215216/**217* The reply the server sent to us for HELO.218* If null, no HELO string has yet been received.219*220* @var string|null221*/222protected $helo_rply;223224/**225* The set of SMTP extensions sent in reply to EHLO command.226* Indexes of the array are extension names.227* Value at index 'HELO' or 'EHLO' (according to command that was sent)228* represents the server name. In case of HELO it is the only element of the array.229* Other values can be boolean TRUE or an array containing extension options.230* If null, no HELO/EHLO string has yet been received.231*232* @var array|null233*/234protected $server_caps;235236/**237* The most recent reply received from the server.238*239* @var string240*/241protected $last_reply = '';242243/**244* Output debugging info via a user-selected method.245*246* @param string $str Debug string to output247* @param int $level The debug level of this message; see DEBUG_* constants248*249* @see SMTP::$Debugoutput250* @see SMTP::$do_debug251*/252protected function edebug($str, $level = 0)253{254if ($level > $this->do_debug) {255return;256}257//Is this a PSR-3 logger?258if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) {259$this->Debugoutput->debug($str);260261return;262}263//Avoid clash with built-in function names264if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) {265call_user_func($this->Debugoutput, $str, $level);266267return;268}269switch ($this->Debugoutput) {270case 'error_log':271//Don't output, just log272error_log($str);273break;274case 'html':275//Cleans up output a bit for a better looking, HTML-safe output276echo gmdate('Y-m-d H:i:s'), ' ', htmlentities(277preg_replace('/[\r\n]+/', '', $str),278ENT_QUOTES,279'UTF-8'280), "<br>\n";281break;282case 'echo':283default:284//Normalize line breaks285$str = preg_replace('/\r\n|\r/m', "\n", $str);286echo gmdate('Y-m-d H:i:s'),287"\t",288//Trim trailing space289trim(290//Indent for readability, except for trailing break291str_replace(292"\n",293"\n \t ",294trim($str)295)296),297"\n";298}299}300301/**302* Connect to an SMTP server.303*304* @param string $host SMTP server IP or host name305* @param int $port The port number to connect to306* @param int $timeout How long to wait for the connection to open307* @param array $options An array of options for stream_context_create()308*309* @return bool310*/311public function connect($host, $port = null, $timeout = 30, $options = [])312{313// Clear errors to avoid confusion314$this->setError('');315// Make sure we are __not__ connected316if ($this->connected()) {317// Already connected, generate error318$this->setError('Already connected to a server');319320return false;321}322if (empty($port)) {323$port = self::DEFAULT_PORT;324}325// Connect to the SMTP server326$this->edebug(327"Connection: opening to $host:$port, timeout=$timeout, options=" .328(count($options) > 0 ? var_export($options, true) : 'array()'),329self::DEBUG_CONNECTION330);331332$this->smtp_conn = $this->getSMTPConnection($host, $port, $timeout, $options);333334if ($this->smtp_conn === false) {335//Error info already set inside `getSMTPConnection()`336return false;337}338339$this->edebug('Connection: opened', self::DEBUG_CONNECTION);340341// Get any announcement342$this->last_reply = $this->get_lines();343$this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);344345return true;346}347348/**349* Create connection to the SMTP server.350*351* @param string $host SMTP server IP or host name352* @param int $port The port number to connect to353* @param int $timeout How long to wait for the connection to open354* @param array $options An array of options for stream_context_create()355*356* @return false|resource357*/358protected function getSMTPConnection($host, $port = null, $timeout = 30, $options = [])359{360static $streamok;361//This is enabled by default since 5.0.0 but some providers disable it362//Check this once and cache the result363if (null === $streamok) {364$streamok = function_exists('stream_socket_client');365}366367$errno = 0;368$errstr = '';369if ($streamok) {370$socket_context = stream_context_create($options);371set_error_handler([$this, 'errorHandler']);372$connection = stream_socket_client(373$host . ':' . $port,374$errno,375$errstr,376$timeout,377STREAM_CLIENT_CONNECT,378$socket_context379);380restore_error_handler();381} else {382//Fall back to fsockopen which should work in more places, but is missing some features383$this->edebug(384'Connection: stream_socket_client not available, falling back to fsockopen',385self::DEBUG_CONNECTION386);387set_error_handler([$this, 'errorHandler']);388$connection = fsockopen(389$host,390$port,391$errno,392$errstr,393$timeout394);395restore_error_handler();396}397398// Verify we connected properly399if (!is_resource($connection)) {400$this->setError(401'Failed to connect to server',402'',403(string) $errno,404$errstr405);406$this->edebug(407'SMTP ERROR: ' . $this->error['error']408. ": $errstr ($errno)",409self::DEBUG_CLIENT410);411412return false;413}414415// SMTP server can take longer to respond, give longer timeout for first read416// Windows does not have support for this timeout function417if (strpos(PHP_OS, 'WIN') !== 0) {418$max = (int)ini_get('max_execution_time');419// Don't bother if unlimited, or if set_time_limit is disabled420if (0 !== $max && $timeout > $max && strpos(ini_get('disable_functions'), 'set_time_limit') === false) {421@set_time_limit($timeout);422}423stream_set_timeout($connection, $timeout, 0);424}425426return $connection;427}428429/**430* Initiate a TLS (encrypted) session.431*432* @return bool433*/434public function startTLS()435{436if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {437return false;438}439440//Allow the best TLS version(s) we can441$crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;442443//PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT444//so add them back in manually if we can445if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {446$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;447$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;448}449450// Begin encrypted connection451set_error_handler([$this, 'errorHandler']);452$crypto_ok = stream_socket_enable_crypto(453$this->smtp_conn,454true,455$crypto_method456);457restore_error_handler();458459return (bool) $crypto_ok;460}461462/**463* Perform SMTP authentication.464* Must be run after hello().465*466* @see hello()467*468* @param string $username The user name469* @param string $password The password470* @param string $authtype The auth type (CRAM-MD5, PLAIN, LOGIN, XOAUTH2)471* @param OAuth $OAuth An optional OAuth instance for XOAUTH2 authentication472*473* @return bool True if successfully authenticated474*/475public function authenticate(476$username,477$password,478$authtype = null,479$OAuth = null480) {481if (!$this->server_caps) {482$this->setError('Authentication is not allowed before HELO/EHLO');483484return false;485}486487if (array_key_exists('EHLO', $this->server_caps)) {488// SMTP extensions are available; try to find a proper authentication method489if (!array_key_exists('AUTH', $this->server_caps)) {490$this->setError('Authentication is not allowed at this stage');491// 'at this stage' means that auth may be allowed after the stage changes492// e.g. after STARTTLS493494return false;495}496497$this->edebug('Auth method requested: ' . ($authtype ?: 'UNSPECIFIED'), self::DEBUG_LOWLEVEL);498$this->edebug(499'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),500self::DEBUG_LOWLEVEL501);502503//If we have requested a specific auth type, check the server supports it before trying others504if (null !== $authtype && !in_array($authtype, $this->server_caps['AUTH'], true)) {505$this->edebug('Requested auth method not available: ' . $authtype, self::DEBUG_LOWLEVEL);506$authtype = null;507}508509if (empty($authtype)) {510//If no auth mechanism is specified, attempt to use these, in this order511//Try CRAM-MD5 first as it's more secure than the others512foreach (['CRAM-MD5', 'LOGIN', 'PLAIN', 'XOAUTH2'] as $method) {513if (in_array($method, $this->server_caps['AUTH'], true)) {514$authtype = $method;515break;516}517}518if (empty($authtype)) {519$this->setError('No supported authentication methods found');520521return false;522}523$this->edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL);524}525526if (!in_array($authtype, $this->server_caps['AUTH'], true)) {527$this->setError("The requested authentication method \"$authtype\" is not supported by the server");528529return false;530}531} elseif (empty($authtype)) {532$authtype = 'LOGIN';533}534switch ($authtype) {535case 'PLAIN':536// Start authentication537if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {538return false;539}540// Send encoded username and password541if (!$this->sendCommand(542'User & Password',543base64_encode("\0" . $username . "\0" . $password),544235545)546) {547return false;548}549break;550case 'LOGIN':551// Start authentication552if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {553return false;554}555if (!$this->sendCommand('Username', base64_encode($username), 334)) {556return false;557}558if (!$this->sendCommand('Password', base64_encode($password), 235)) {559return false;560}561break;562case 'CRAM-MD5':563// Start authentication564if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {565return false;566}567// Get the challenge568$challenge = base64_decode(substr($this->last_reply, 4));569570// Build the response571$response = $username . ' ' . $this->hmac($challenge, $password);572573// send encoded credentials574return $this->sendCommand('Username', base64_encode($response), 235);575case 'XOAUTH2':576//The OAuth instance must be set up prior to requesting auth.577if (null === $OAuth) {578return false;579}580$oauth = $OAuth->getOauth64();581582// Start authentication583if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {584return false;585}586break;587default:588$this->setError("Authentication method \"$authtype\" is not supported");589590return false;591}592593return true;594}595596/**597* Calculate an MD5 HMAC hash.598* Works like hash_hmac('md5', $data, $key)599* in case that function is not available.600*601* @param string $data The data to hash602* @param string $key The key to hash with603*604* @return string605*/606protected function hmac($data, $key)607{608if (function_exists('hash_hmac')) {609return hash_hmac('md5', $data, $key);610}611612// The following borrowed from613// http://php.net/manual/en/function.mhash.php#27225614615// RFC 2104 HMAC implementation for php.616// Creates an md5 HMAC.617// Eliminates the need to install mhash to compute a HMAC618// by Lance Rushing619620$bytelen = 64; // byte length for md5621if (strlen($key) > $bytelen) {622$key = pack('H*', md5($key));623}624$key = str_pad($key, $bytelen, chr(0x00));625$ipad = str_pad('', $bytelen, chr(0x36));626$opad = str_pad('', $bytelen, chr(0x5c));627$k_ipad = $key ^ $ipad;628$k_opad = $key ^ $opad;629630return md5($k_opad . pack('H*', md5($k_ipad . $data)));631}632633/**634* Check connection state.635*636* @return bool True if connected637*/638public function connected()639{640if (is_resource($this->smtp_conn)) {641$sock_status = stream_get_meta_data($this->smtp_conn);642if ($sock_status['eof']) {643// The socket is valid but we are not connected644$this->edebug(645'SMTP NOTICE: EOF caught while checking if connected',646self::DEBUG_CLIENT647);648$this->close();649650return false;651}652653return true; // everything looks good654}655656return false;657}658659/**660* Close the socket and clean up the state of the class.661* Don't use this function without first trying to use QUIT.662*663* @see quit()664*/665public function close()666{667$this->setError('');668$this->server_caps = null;669$this->helo_rply = null;670if (is_resource($this->smtp_conn)) {671// close the connection and cleanup672fclose($this->smtp_conn);673$this->smtp_conn = null; //Makes for cleaner serialization674$this->edebug('Connection: closed', self::DEBUG_CONNECTION);675}676}677678/**679* Send an SMTP DATA command.680* Issues a data command and sends the msg_data to the server,681* finializing the mail transaction. $msg_data is the message682* that is to be send with the headers. Each header needs to be683* on a single line followed by a <CRLF> with the message headers684* and the message body being separated by an additional <CRLF>.685* Implements RFC 821: DATA <CRLF>.686*687* @param string $msg_data Message data to send688*689* @return bool690*/691public function data($msg_data)692{693//This will use the standard timelimit694if (!$this->sendCommand('DATA', 'DATA', 354)) {695return false;696}697698/* The server is ready to accept data!699* According to rfc821 we should not send more than 1000 characters on a single line (including the LE)700* so we will break the data up into lines by \r and/or \n then if needed we will break each of those into701* smaller lines to fit within the limit.702* We will also look for lines that start with a '.' and prepend an additional '.'.703* NOTE: this does not count towards line-length limit.704*/705706// Normalize line breaks before exploding707$lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $msg_data));708709/* To distinguish between a complete RFC822 message and a plain message body, we check if the first field710* of the first line (':' separated) does not contain a space then it _should_ be a header and we will711* process all lines before a blank line as headers.712*/713714$field = substr($lines[0], 0, strpos($lines[0], ':'));715$in_headers = false;716if (!empty($field) && strpos($field, ' ') === false) {717$in_headers = true;718}719720foreach ($lines as $line) {721$lines_out = [];722if ($in_headers && $line === '') {723$in_headers = false;724}725//Break this line up into several smaller lines if it's too long726//Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),727while (isset($line[self::MAX_LINE_LENGTH])) {728//Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on729//so as to avoid breaking in the middle of a word730$pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');731//Deliberately matches both false and 0732if (!$pos) {733//No nice break found, add a hard break734$pos = self::MAX_LINE_LENGTH - 1;735$lines_out[] = substr($line, 0, $pos);736$line = substr($line, $pos);737} else {738//Break at the found point739$lines_out[] = substr($line, 0, $pos);740//Move along by the amount we dealt with741$line = substr($line, $pos + 1);742}743//If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1744if ($in_headers) {745$line = "\t" . $line;746}747}748$lines_out[] = $line;749750//Send the lines to the server751foreach ($lines_out as $line_out) {752//RFC2821 section 4.5.2753if (!empty($line_out) && $line_out[0] === '.') {754$line_out = '.' . $line_out;755}756$this->client_send($line_out . static::LE, 'DATA');757}758}759760//Message data has been sent, complete the command761//Increase timelimit for end of DATA command762$savetimelimit = $this->Timelimit;763$this->Timelimit *= 2;764$result = $this->sendCommand('DATA END', '.', 250);765$this->recordLastTransactionID();766//Restore timelimit767$this->Timelimit = $savetimelimit;768769return $result;770}771772/**773* Send an SMTP HELO or EHLO command.774* Used to identify the sending server to the receiving server.775* This makes sure that client and server are in a known state.776* Implements RFC 821: HELO <SP> <domain> <CRLF>777* and RFC 2821 EHLO.778*779* @param string $host The host name or IP to connect to780*781* @return bool782*/783public function hello($host = '')784{785//Try extended hello first (RFC 2821)786return $this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host);787}788789/**790* Send an SMTP HELO or EHLO command.791* Low-level implementation used by hello().792*793* @param string $hello The HELO string794* @param string $host The hostname to say we are795*796* @return bool797*798* @see hello()799*/800protected function sendHello($hello, $host)801{802$noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);803$this->helo_rply = $this->last_reply;804if ($noerror) {805$this->parseHelloFields($hello);806} else {807$this->server_caps = null;808}809810return $noerror;811}812813/**814* Parse a reply to HELO/EHLO command to discover server extensions.815* In case of HELO, the only parameter that can be discovered is a server name.816*817* @param string $type `HELO` or `EHLO`818*/819protected function parseHelloFields($type)820{821$this->server_caps = [];822$lines = explode("\n", $this->helo_rply);823824foreach ($lines as $n => $s) {825//First 4 chars contain response code followed by - or space826$s = trim(substr($s, 4));827if (empty($s)) {828continue;829}830$fields = explode(' ', $s);831if (!empty($fields)) {832if (!$n) {833$name = $type;834$fields = $fields[0];835} else {836$name = array_shift($fields);837switch ($name) {838case 'SIZE':839$fields = ($fields ? $fields[0] : 0);840break;841case 'AUTH':842if (!is_array($fields)) {843$fields = [];844}845break;846default:847$fields = true;848}849}850$this->server_caps[$name] = $fields;851}852}853}854855/**856* Send an SMTP MAIL command.857* Starts a mail transaction from the email address specified in858* $from. Returns true if successful or false otherwise. If True859* the mail transaction is started and then one or more recipient860* commands may be called followed by a data command.861* Implements RFC 821: MAIL <SP> FROM:<reverse-path> <CRLF>.862*863* @param string $from Source address of this message864*865* @return bool866*/867public function mail($from)868{869$useVerp = ($this->do_verp ? ' XVERP' : '');870871return $this->sendCommand(872'MAIL FROM',873'MAIL FROM:<' . $from . '>' . $useVerp,874250875);876}877878/**879* Send an SMTP QUIT command.880* Closes the socket if there is no error or the $close_on_error argument is true.881* Implements from RFC 821: QUIT <CRLF>.882*883* @param bool $close_on_error Should the connection close if an error occurs?884*885* @return bool886*/887public function quit($close_on_error = true)888{889$noerror = $this->sendCommand('QUIT', 'QUIT', 221);890$err = $this->error; //Save any error891if ($noerror || $close_on_error) {892$this->close();893$this->error = $err; //Restore any error from the quit command894}895896return $noerror;897}898899/**900* Send an SMTP RCPT command.901* Sets the TO argument to $toaddr.902* Returns true if the recipient was accepted false if it was rejected.903* Implements from RFC 821: RCPT <SP> TO:<forward-path> <CRLF>.904*905* @param string $address The address the message is being sent to906* @param string $dsn Comma separated list of DSN notifications. NEVER, SUCCESS, FAILURE907* or DELAY. If you specify NEVER all other notifications are ignored.908*909* @return bool910*/911public function recipient($address, $dsn = '')912{913if (empty($dsn)) {914$rcpt = 'RCPT TO:<' . $address . '>';915} else {916$dsn = strtoupper($dsn);917$notify = [];918919if (strpos($dsn, 'NEVER') !== false) {920$notify[] = 'NEVER';921} else {922foreach (['SUCCESS', 'FAILURE', 'DELAY'] as $value) {923if (strpos($dsn, $value) !== false) {924$notify[] = $value;925}926}927}928929$rcpt = 'RCPT TO:<' . $address . '> NOTIFY=' . implode(',', $notify);930}931932return $this->sendCommand(933'RCPT TO',934$rcpt,935[250, 251]936);937}938939/**940* Send an SMTP RSET command.941* Abort any transaction that is currently in progress.942* Implements RFC 821: RSET <CRLF>.943*944* @return bool True on success945*/946public function reset()947{948return $this->sendCommand('RSET', 'RSET', 250);949}950951/**952* Send a command to an SMTP server and check its return code.953*954* @param string $command The command name - not sent to the server955* @param string $commandstring The actual command to send956* @param int|array $expect One or more expected integer success codes957*958* @return bool True on success959*/960protected function sendCommand($command, $commandstring, $expect)961{962if (!$this->connected()) {963$this->setError("Called $command without being connected");964965return false;966}967//Reject line breaks in all commands968if ((strpos($commandstring, "\n") !== false) || (strpos($commandstring, "\r") !== false)) {969$this->setError("Command '$command' contained line breaks");970971return false;972}973$this->client_send($commandstring . static::LE, $command);974975$this->last_reply = $this->get_lines();976// Fetch SMTP code and possible error code explanation977$matches = [];978if (preg_match('/^([\d]{3})[ -](?:([\d]\\.[\d]\\.[\d]{1,2}) )?/', $this->last_reply, $matches)) {979$code = (int) $matches[1];980$code_ex = (count($matches) > 2 ? $matches[2] : null);981// Cut off error code from each response line982$detail = preg_replace(983"/{$code}[ -]" .984($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . '/m',985'',986$this->last_reply987);988} else {989// Fall back to simple parsing if regex fails990$code = (int) substr($this->last_reply, 0, 3);991$code_ex = null;992$detail = substr($this->last_reply, 4);993}994995$this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);996997if (!in_array($code, (array) $expect, true)) {998$this->setError(999"$command command failed",1000$detail,1001$code,1002$code_ex1003);1004$this->edebug(1005'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,1006self::DEBUG_CLIENT1007);10081009return false;1010}10111012$this->setError('');10131014return true;1015}10161017/**1018* Send an SMTP SAML command.1019* Starts a mail transaction from the email address specified in $from.1020* Returns true if successful or false otherwise. If True1021* the mail transaction is started and then one or more recipient1022* commands may be called followed by a data command. This command1023* will send the message to the users terminal if they are logged1024* in and send them an email.1025* Implements RFC 821: SAML <SP> FROM:<reverse-path> <CRLF>.1026*1027* @param string $from The address the message is from1028*1029* @return bool1030*/1031public function sendAndMail($from)1032{1033return $this->sendCommand('SAML', "SAML FROM:$from", 250);1034}10351036/**1037* Send an SMTP VRFY command.1038*1039* @param string $name The name to verify1040*1041* @return bool1042*/1043public function verify($name)1044{1045return $this->sendCommand('VRFY', "VRFY $name", [250, 251]);1046}10471048/**1049* Send an SMTP NOOP command.1050* Used to keep keep-alives alive, doesn't actually do anything.1051*1052* @return bool1053*/1054public function noop()1055{1056return $this->sendCommand('NOOP', 'NOOP', 250);1057}10581059/**1060* Send an SMTP TURN command.1061* This is an optional command for SMTP that this class does not support.1062* This method is here to make the RFC821 Definition complete for this class1063* and _may_ be implemented in future.1064* Implements from RFC 821: TURN <CRLF>.1065*1066* @return bool1067*/1068public function turn()1069{1070$this->setError('The SMTP TURN command is not implemented');1071$this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);10721073return false;1074}10751076/**1077* Send raw data to the server.1078*1079* @param string $data The data to send1080* @param string $command Optionally, the command this is part of, used only for controlling debug output1081*1082* @return int|bool The number of bytes sent to the server or false on error1083*/1084public function client_send($data, $command = '')1085{1086//If SMTP transcripts are left enabled, or debug output is posted online1087//it can leak credentials, so hide credentials in all but lowest level1088if (self::DEBUG_LOWLEVEL > $this->do_debug &&1089in_array($command, ['User & Password', 'Username', 'Password'], true)) {1090$this->edebug('CLIENT -> SERVER: [credentials hidden]', self::DEBUG_CLIENT);1091} else {1092$this->edebug('CLIENT -> SERVER: ' . $data, self::DEBUG_CLIENT);1093}1094set_error_handler([$this, 'errorHandler']);1095$result = fwrite($this->smtp_conn, $data);1096restore_error_handler();10971098return $result;1099}11001101/**1102* Get the latest error.1103*1104* @return array1105*/1106public function getError()1107{1108return $this->error;1109}11101111/**1112* Get SMTP extensions available on the server.1113*1114* @return array|null1115*/1116public function getServerExtList()1117{1118return $this->server_caps;1119}11201121/**1122* Get metadata about the SMTP server from its HELO/EHLO response.1123* The method works in three ways, dependent on argument value and current state:1124* 1. HELO/EHLO has not been sent - returns null and populates $this->error.1125* 2. HELO has been sent -1126* $name == 'HELO': returns server name1127* $name == 'EHLO': returns boolean false1128* $name == any other string: returns null and populates $this->error1129* 3. EHLO has been sent -1130* $name == 'HELO'|'EHLO': returns the server name1131* $name == any other string: if extension $name exists, returns True1132* or its options (e.g. AUTH mechanisms supported). Otherwise returns False.1133*1134* @param string $name Name of SMTP extension or 'HELO'|'EHLO'1135*1136* @return string|bool|null1137*/1138public function getServerExt($name)1139{1140if (!$this->server_caps) {1141$this->setError('No HELO/EHLO was sent');11421143return;1144}11451146if (!array_key_exists($name, $this->server_caps)) {1147if ('HELO' === $name) {1148return $this->server_caps['EHLO'];1149}1150if ('EHLO' === $name || array_key_exists('EHLO', $this->server_caps)) {1151return false;1152}1153$this->setError('HELO handshake was used; No information about server extensions available');11541155return;1156}11571158return $this->server_caps[$name];1159}11601161/**1162* Get the last reply from the server.1163*1164* @return string1165*/1166public function getLastReply()1167{1168return $this->last_reply;1169}11701171/**1172* Read the SMTP server's response.1173* Either before eof or socket timeout occurs on the operation.1174* With SMTP we can tell if we have more lines to read if the1175* 4th character is '-' symbol. If it is a space then we don't1176* need to read anything else.1177*1178* @return string1179*/1180protected function get_lines()1181{1182// If the connection is bad, give up straight away1183if (!is_resource($this->smtp_conn)) {1184return '';1185}1186$data = '';1187$endtime = 0;1188stream_set_timeout($this->smtp_conn, $this->Timeout);1189if ($this->Timelimit > 0) {1190$endtime = time() + $this->Timelimit;1191}1192$selR = [$this->smtp_conn];1193$selW = null;1194while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {1195//Must pass vars in here as params are by reference1196//solution for signals inspired by https://github.com/symfony/symfony/pull/65401197set_error_handler([$this, 'errorHandler']);1198$n = stream_select($selR, $selW, $selW, $this->Timelimit);1199restore_error_handler();12001201if ($n === false) {1202$message = $this->getError()['detail'];12031204$this->edebug(1205'SMTP -> get_lines(): select failed (' . $message . ')',1206self::DEBUG_LOWLEVEL1207);12081209//stream_select returns false when the `select` system call is interrupted by an incoming signal, try the select again1210if (stripos($message, 'interrupted system call') !== false) {1211$this->edebug(1212'SMTP -> get_lines(): retrying stream_select',1213self::DEBUG_LOWLEVEL1214);1215$this->setError('');1216continue;1217}12181219break;1220}12211222if (!$n) {1223$this->edebug(1224'SMTP -> get_lines(): select timed-out in (' . $this->Timelimit . ' sec)',1225self::DEBUG_LOWLEVEL1226);1227break;1228}12291230//Deliberate noise suppression - errors are handled afterwards1231$str = @fgets($this->smtp_conn, self::MAX_REPLY_LENGTH);1232$this->edebug('SMTP INBOUND: "' . trim($str) . '"', self::DEBUG_LOWLEVEL);1233$data .= $str;1234// If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled),1235// or 4th character is a space or a line break char, we are done reading, break the loop.1236// String array access is a significant micro-optimisation over strlen1237if (!isset($str[3]) || $str[3] === ' ' || $str[3] === "\r" || $str[3] === "\n") {1238break;1239}1240// Timed-out? Log and break1241$info = stream_get_meta_data($this->smtp_conn);1242if ($info['timed_out']) {1243$this->edebug(1244'SMTP -> get_lines(): stream timed-out (' . $this->Timeout . ' sec)',1245self::DEBUG_LOWLEVEL1246);1247break;1248}1249// Now check if reads took too long1250if ($endtime && time() > $endtime) {1251$this->edebug(1252'SMTP -> get_lines(): timelimit reached (' .1253$this->Timelimit . ' sec)',1254self::DEBUG_LOWLEVEL1255);1256break;1257}1258}12591260return $data;1261}12621263/**1264* Enable or disable VERP address generation.1265*1266* @param bool $enabled1267*/1268public function setVerp($enabled = false)1269{1270$this->do_verp = $enabled;1271}12721273/**1274* Get VERP address generation mode.1275*1276* @return bool1277*/1278public function getVerp()1279{1280return $this->do_verp;1281}12821283/**1284* Set error messages and codes.1285*1286* @param string $message The error message1287* @param string $detail Further detail on the error1288* @param string $smtp_code An associated SMTP error code1289* @param string $smtp_code_ex Extended SMTP code1290*/1291protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')1292{1293$this->error = [1294'error' => $message,1295'detail' => $detail,1296'smtp_code' => $smtp_code,1297'smtp_code_ex' => $smtp_code_ex,1298];1299}13001301/**1302* Set debug output method.1303*1304* @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it1305*/1306public function setDebugOutput($method = 'echo')1307{1308$this->Debugoutput = $method;1309}13101311/**1312* Get debug output method.1313*1314* @return string1315*/1316public function getDebugOutput()1317{1318return $this->Debugoutput;1319}13201321/**1322* Set debug output level.1323*1324* @param int $level1325*/1326public function setDebugLevel($level = 0)1327{1328$this->do_debug = $level;1329}13301331/**1332* Get debug output level.1333*1334* @return int1335*/1336public function getDebugLevel()1337{1338return $this->do_debug;1339}13401341/**1342* Set SMTP timeout.1343*1344* @param int $timeout The timeout duration in seconds1345*/1346public function setTimeout($timeout = 0)1347{1348$this->Timeout = $timeout;1349}13501351/**1352* Get SMTP timeout.1353*1354* @return int1355*/1356public function getTimeout()1357{1358return $this->Timeout;1359}13601361/**1362* Reports an error number and string.1363*1364* @param int $errno The error number returned by PHP1365* @param string $errmsg The error message returned by PHP1366* @param string $errfile The file the error occurred in1367* @param int $errline The line number the error occurred on1368*/1369protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0)1370{1371$notice = 'Connection failed.';1372$this->setError(1373$notice,1374$errmsg,1375(string) $errno1376);1377$this->edebug(1378"$notice Error #$errno: $errmsg [$errfile line $errline]",1379self::DEBUG_CONNECTION1380);1381}13821383/**1384* Extract and return the ID of the last SMTP transaction based on1385* a list of patterns provided in SMTP::$smtp_transaction_id_patterns.1386* Relies on the host providing the ID in response to a DATA command.1387* If no reply has been received yet, it will return null.1388* If no pattern was matched, it will return false.1389*1390* @return bool|string|null1391*/1392protected function recordLastTransactionID()1393{1394$reply = $this->getLastReply();13951396if (empty($reply)) {1397$this->last_smtp_transaction_id = null;1398} else {1399$this->last_smtp_transaction_id = false;1400foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {1401$matches = [];1402if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {1403$this->last_smtp_transaction_id = trim($matches[1]);1404break;1405}1406}1407}14081409return $this->last_smtp_transaction_id;1410}14111412/**1413* Get the queue/transaction ID of the last SMTP transaction1414* If no reply has been received yet, it will return null.1415* If no pattern was matched, it will return false.1416*1417* @return bool|string|null1418*1419* @see recordLastTransactionID()1420*/1421public function getLastTransactionID()1422{1423return $this->last_smtp_transaction_id;1424}1425}142614271428