: str_replace(): Passing null to parameter #2 ($replace) of type array|string is deprecated in
* @param string $username The user name
* @param string $password The password
* @param string $authtype The auth type (CRAM-MD5, PLAIN, LOGIN, XOAUTH2)
* @param OAuthTokenProvider $OAuth An optional OAuthTokenProvider instance for XOAUTH2 authentication
* @return bool True if successfully authenticated
public function authenticate(
if (!$this->server_caps) {
$this->setError('Authentication is not allowed before HELO/EHLO');
if (array_key_exists('EHLO', $this->server_caps)) {
//SMTP extensions are available; try to find a proper authentication method
if (!array_key_exists('AUTH', $this->server_caps)) {
$this->setError('Authentication is not allowed at this stage');
//'at this stage' means that auth may be allowed after the stage changes
$this->edebug('Auth method requested: ' . ($authtype ?: 'UNSPECIFIED'), self::DEBUG_LOWLEVEL);
'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
//If we have requested a specific auth type, check the server supports it before trying others
if (null !== $authtype && !in_array($authtype, $this->server_caps['AUTH'], true)) {
$this->edebug('Requested auth method not available: ' . $authtype, self::DEBUG_LOWLEVEL);
//If no auth mechanism is specified, attempt to use these, in this order
//Try CRAM-MD5 first as it's more secure than the others
foreach (['CRAM-MD5', 'LOGIN', 'PLAIN', 'XOAUTH2'] as $method) {
if (in_array($method, $this->server_caps['AUTH'], true)) {
$this->setError('No supported authentication methods found');
$this->edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL);
if (!in_array($authtype, $this->server_caps['AUTH'], true)) {
$this->setError("The requested authentication method \"$authtype\" is not supported by the server");
} elseif (empty($authtype)) {
if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
//Send encoded username and password
//Format from https://tools.ietf.org/html/rfc4616#section-2
//We skip the first field (it's forgery), so the string starts with a null byte
base64_encode("\0" . $username . "\0" . $password),
if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
if (!$this->sendCommand('Username', base64_encode($username), 334)) {
if (!$this->sendCommand('Password', base64_encode($password), 235)) {
if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
$challenge = base64_decode(substr($this->last_reply, 4));
$response = $username . ' ' . $this->hmac($challenge, $password);
//send encoded credentials
return $this->sendCommand('Username', base64_encode($response), 235);
//The OAuth instance must be set up prior to requesting auth.
$oauth = $OAuth->getOauth64();
if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
$this->setError("Authentication method \"$authtype\" is not supported");
* Calculate an MD5 HMAC hash.
* Works like hash_hmac('md5', $data, $key)
* in case that function is not available.
* @param string $data The data to hash
* @param string $key The key to hash with
protected function hmac($data, $key)
if (function_exists('hash_hmac')) {
return hash_hmac('md5', $data, $key);
//The following borrowed from
//http://php.net/manual/en/function.mhash.php#27225
//RFC 2104 HMAC implementation for php.
//Eliminates the need to install mhash to compute a HMAC
$bytelen = 64; //byte length for md5
if (strlen($key) > $bytelen) {
$key = pack('H*', md5($key));
$key = str_pad($key, $bytelen, chr(0x00));
$ipad = str_pad('', $bytelen, chr(0x36));
$opad = str_pad('', $bytelen, chr(0x5c));
return md5($k_opad . pack('H*', md5($k_ipad . $data)));
* Check connection state.
* @return bool True if connected
public function connected()
if (is_resource($this->smtp_conn)) {
$sock_status = stream_get_meta_data($this->smtp_conn);
if ($sock_status['eof']) {
//The socket is valid but we are not connected
'SMTP NOTICE: EOF caught while checking if connected',
return true; //everything looks good
* Close the socket and clean up the state of the class.
* Don't use this function without first trying to use QUIT.
$this->server_caps = null;
if (is_resource($this->smtp_conn)) {
//Close the connection and cleanup
fclose($this->smtp_conn);
$this->smtp_conn = null; //Makes for cleaner serialization
$this->edebug('Connection: closed', self::DEBUG_CONNECTION);
* Send an SMTP DATA command.
* Issues a data command and sends the msg_data to the server,
* finalizing the mail transaction. $msg_data is the message
* that is to be sent with the headers. Each header needs to be
* on a single line followed by a <CRLF> with the message headers
* and the message body being separated by an additional <CRLF>.
* Implements RFC 821: DATA <CRLF>.
* @param string $msg_data Message data to send
public function data($msg_data)
//This will use the standard timelimit
if (!$this->sendCommand('DATA', 'DATA', 354)) {
/* The server is ready to accept data!
* According to rfc821 we should not send more than 1000 characters on a single line (including the LE)
* so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
* smaller lines to fit within the limit.
* We will also look for lines that start with a '.' and prepend an additional '.'.
* NOTE: this does not count towards line-length limit.
//Normalize line breaks before exploding
$lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $msg_data));
/* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
* of the first line (':' separated) does not contain a space then it _should_ be a header, and we will
* process all lines before a blank line as headers.
$field = substr($lines[0], 0, strpos($lines[0], ':'));
if (!empty($field) && strpos($field, ' ') === false) {
foreach ($lines as $line) {
if ($in_headers && $line === '') {
//Break this line up into several smaller lines if it's too long
//Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
while (isset($line[self::MAX_LINE_LENGTH])) {
//Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
//so as to avoid breaking in the middle of a word
$pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
//Deliberately matches both false and 0
//No nice break found, add a hard break
$pos = self::MAX_LINE_LENGTH - 1;
$lines_out[] = substr($line, 0, $pos);
$line = substr($line, $pos);
//Break at the found point
$lines_out[] = substr($line, 0, $pos);
//Move along by the amount we dealt with
$line = substr($line, $pos + 1);
//If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
//Send the lines to the server
foreach ($lines_out as $line_out) {
//Dot-stuffing as per RFC5321 section 4.5.2
//https://tools.ietf.org/html/rfc5321#section-4.5.2
if (!empty($line_out) && $line_out[0] === '.') {
$line_out = '.' . $line_out;
$this->client_send($line_out . static::LE, 'DATA');
//Message data has been sent, complete the command
//Increase timelimit for end of DATA command
$savetimelimit = $this->Timelimit;
$result = $this->sendCommand('DATA END', '.', 250);
$this->recordLastTransactionID();
$this->Timelimit = $savetimelimit;
* Send an SMTP HELO or EHLO command.
* Used to identify the sending server to the receiving server.
* This makes sure that client and server are in a known state.
* Implements RFC 821: HELO <SP> <domain> <CRLF>
* @param string $host The host name or IP to connect to
public function hello($host = '')
//Try extended hello first (RFC 2821)
if ($this->sendHello('EHLO', $host)) {
//Some servers shut down the SMTP service here (RFC 5321)
if (substr($this->helo_rply, 0, 3) == '421') {
return $this->sendHello('HELO', $host);
* Send an SMTP HELO or EHLO command.
* Low-level implementation used by hello().
* @param string $hello The HELO string
* @param string $host The hostname to say we are
protected function sendHello($hello, $host)
$noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
$this->helo_rply = $this->last_reply;
$this->parseHelloFields($hello);
$this->server_caps = null;
* Parse a reply to HELO/EHLO command to discover server extensions.
* In case of HELO, the only parameter that can be discovered is a server name.
* @param string $type `HELO` or `EHLO`
protected function parseHelloFields($type)
$lines = explode("\n", $this->helo_rply);
foreach ($lines as $n => $s) {
//First 4 chars contain response code followed by - or space
$s = trim(substr($s, 4));
$fields = explode(' ', $s);
$name = array_shift($fields);
$fields = ($fields ? $fields[0] : 0);
if (!is_array($fields)) {
$this->server_caps[$name] = $fields;
* Send an SMTP MAIL command.
* Starts a mail transaction from the email address specified in
* $from. Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more recipient
* commands may be called followed by a data command.
* Implements RFC 821: MAIL <SP> FROM:<reverse-path> <CRLF>.
* @param string $from Source address of this message
public function mail($from)
$useVerp = ($this->do_verp ? ' XVERP' : '');
return $this->sendCommand(
'MAIL FROM:<' . $from . '>' . $useVerp,
* Send an SMTP QUIT command.
* Closes the socket if there is no error or the $close_on_error argument is true.
* Implements from RFC 821: QUIT <CRLF>.
* @param bool $close_on_error Should the connection close if an error occurs?
public function quit($close_on_error = true)
$noerror = $this->sendCommand('QUIT', 'QUIT', 221);
$err = $this->error; //Save any error
if ($noerror || $close_on_error) {
$this->error = $err; //Restore any error from the quit command
* Send an SMTP RCPT command.
* Sets the TO argument to $toaddr.
* Returns true if the recipient was accepted false if it was rejected.
* Implements from RFC 821: RCPT <SP> TO:<forward-path> <CRLF>.
* @param string $address The address the message is being sent to
* @param string $dsn Comma separated list of DSN notifications. NEVER, SUCCESS, FAILURE
* or DELAY. If you specify NEVER all other notifications are ignored.
public function recipient($address, $dsn = '')
$rcpt = 'RCPT TO:<' . $address . '>';
if (strpos($dsn, 'NEVER') !== false) {
foreach (['SUCCESS', 'FAILURE', 'DELAY'] as $value) {
if (strpos($dsn, $value) !== false) {
$rcpt = 'RCPT TO:<' . $address . '> NOTIFY=' . implode(',', $notify);
return $this->sendCommand(
* Send SMTP XCLIENT command to server and check its return code.
* @return bool True on success
public function xclient(array $vars)
foreach ($vars as $key => $value) {
if (in_array($key, SMTP::$xclient_allowed_attributes)) {
$xclient_options .= " {$key}={$value}";