Source for file SMTP2.php
Documentation is available at SMTP2.php
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Chuck Hagenbuch <chuck@horde.org> |
// | Jon Parise <jon@php.net> |
// | Damian Alejandro Fernandez Sosa <damlists@cnba.uba.ar> |
// +----------------------------------------------------------------------+
require_once 'PEAR/Exception.php';
require_once 'Net/Socket2.php';
* Provides an implementation of the SMTP protocol using PEAR's
* @author Chuck Hagenbuch <chuck@horde.org>
* @author Jon Parise <jon@php.net>
* @author Damian Alejandro Fernandez Sosa <damlists@cnba.uba.ar>
* @example basic.php A basic implementation of the Net_SMTP2 package.
* The server to connect to.
public $host = 'localhost';
* The port to connect to.
* The value to give when sending EHLO or HELO.
* List of supported authentication methods, in preferential order.
* Use SMTP command pipelining (specified in RFC 2920) if the SMTP
* When pipeling is enabled, rcptTo(), mailFrom(), sendFrom(),
* somlFrom() and samlFrom() do not wait for a response from the
* SMTP server but return immediately.
* Number of pipelined commands.
* Should debugging output be enabled?
* The socket resource being used to connect to the SMTP server.
* Array of socket options that will be passed to Net_Socket2::connect().
* @see stream_context_create()
* The socket I/O timeout value in seconds.
* The most recent server response code.
* The most recent server response arguments.
* Stores the SMTP server's greeting string.
* Stores detected features of the SMTP server.
* Instantiates a new Net_SMTP2 object, overriding any defaults
* with parameters that are passed in.
* If you have SSL support in PHP, you can connect to a server
* over SSL using an 'ssl://' prefix:
* // 465 is a common smtps port.
* $smtp = new Net_SMTP2('ssl://mail.host.com', 465);
* @param string $host The server to connect to.
* @param integer $port The port to connect to.
* @param string $localhost The value to give when sending EHLO or HELO.
* @param boolean $pipeling Use SMTP command pipelining
* @param integer $timeout Socket I/O timeout in seconds.
* @param array $socket_options Socket stream_context_create() options.
public function __construct($host = null , $port = null , $localhost = null ,
$pipelining = false , $timeout = 0 ,
$this->_socket = new Net_Socket2 ();
/* Include the Auth_SASL2 package. If the package is available, we
* enable the authentication methods that depend upon it. */
if (@include_once 'Auth/SASL2.php') {
$this->setAuthMethod('DIGEST-MD5', array ($this, '_authDigest_MD5'));
/* These standard authentication methods are always available. */
$this->setAuthMethod('LOGIN', array ($this, '_authLogin'), false );
$this->setAuthMethod('PLAIN', array ($this, '_authPlain'), false );
* Set the socket I/O timeout value in seconds plus microseconds.
* @param integer $seconds Timeout value in seconds.
* @param integer $microseconds Additional value in microseconds.
public function setTimeout($seconds, $microseconds = 0 )
return $this->_socket->setTimeout ($seconds, $microseconds);
* Set the value of the debugging flag.
* @param boolean $debug New value for the debugging flag.
public function setDebug($debug, $handler = null )
* Write the given debug text to the current debug output handler.
* @param string $message Debug message text.
protected function _debug($message)
array (&$this, $message));
echo " DEBUG: $message\n";
* Send the given string of data to the server.
* @param string $data The string of data to send.
* @return integer The number of bytes that were actually written.
protected function _send($data)
$result = $this->_socket->write ($data);
throw new PEAR_Exception ('Failed to write to socket: unknown error');
* Send a command to the server with an optional string of
* arguments. A carriage return / linefeed (CRLF) sequence will
* be appended to each command string before it is sent to the
* SMTP server - an error will be thrown if the command string
* already contains any newline characters. Use _send() for
* commands that must contain newlines.
* @param string $command The SMTP command to send to the server.
* @param string $args A string of optional arguments to append
* @return integer The number of bytes that were actually written.
protected function _put($command, $args = '')
throw new PEAR_Exception ('Commands cannot contain newlines');
return $this->_send($command . "\r\n");
* Read a reply from the SMTP server. The reply consists of a response
* code and a response message.
* @param mixed $valid The set of valid response codes. These
* may be specified as an array of integer
* values or as a single integer value.
* @param bool $later Do not parse the response now, but wait
* until the last command in the pipelined
while ($line = $this->_socket->readLine ()) {
/* If we receive an empty line, the connection was closed. */
throw new PEAR_Exception ('Connection was closed');
/* Read the code and store the rest in the arguments array. */
/* Check the syntax of the response code. */
$this->_code = (int) $code;
/* If this is not a multiline response, we're done. */
if (substr($line, 3 , 1 ) != '-') {
/* Compare the server's response code with the valid code/codes. */
throw new PEAR_Exception ('Invalid response code received from server',
* Issue an SMTP command and verify its response.
* @param string $command The SMTP command string or data.
* @param mixed $valid The set of valid response codes. These
* may be specified as an array of integer
* values or as a single integer value.
public function command($command, $valid)
* Return a 2-tuple containing the last response from the SMTP server.
* @return array A two-element array: the first element contains the
* response code as an integer and the second element
* contains the response's arguments as a string.
* Return the SMTP server's greeting string.
* @return string A string containing the greeting string, or null if a
* greeting has not been received.
* Attempt to connect to the SMTP server.
* @param int $timeout The timeout value (in seconds) for the
* socket connection attempt.
* @param bool $persistent Should a persistent socket connection
public function connect($timeout = null , $persistent = false )
* Now that we're connected, reset the socket's timeout value for
* future I/O operations. This allows us to have different socket
* timeout values for the initial connection (our $timeout parameter)
* and all other socket operations.
/* Extract and store a copy of the server's greeting string. */
* Attempt to disconnect from the SMTP server.
} catch (Net_Socket2_Exception $e) {
// Already disconnected? Silence!
* Attempt to send the EHLO command and obtain a list of ESMTP
* extensions available, and failing that just send HELO.
} catch (PEAR_Exception $e) {
/* If the EHLO failed, try the simpler HELO command. */
$verb = strtok($argument, ' ');
$this->_esmtp[$verb] = $arguments;
if (!isset ($this->_esmtp['PIPELINING'])) {
* Returns the name of the best authentication method that the server
* @return mixed Returns a string containing the name of the best
* supported authentication method.
if (in_array($method, $available_methods)) {
throw new PEAR_Exception ('No supported authentication methods');
* Attempt to do SMTP authentication.
* @param string $uid The userid to authenticate as.
* @param string $pwd The password to authenticate with.
* @param string $method The requested authentication method. If none is
* specified, the best supported method will be
* @param bool $tls Flag indicating whether or not TLS should be
* @param string $authz An optional authorization identifier. If
* specified, this identifier will be used as the
public function auth($uid, $pwd, $method = '', $tls = true , $authz = '')
/* We can only attempt a TLS connection if one has been requested,
* we're running PHP 5.1.0 or later, have access to the OpenSSL
* extension, are connected to an SMTP server which supports the
* STARTTLS extension, and aren't already connected over a secure
* (SSL) socket connection. */
/* Start the TLS connection attempt. */
$result = $this->_socket->enableCrypto (true , STREAM_CRYPTO_METHOD_TLS_CLIENT );
throw new PEAR_Exception ('STARTTLS failed');
/* Send EHLO again to recieve the AUTH string from the
if (empty ($this->_esmtp['AUTH'])) {
throw new PEAR_Exception ('SMTP server does not support authentication');
/* If no method has been specified, get the name of the best
* supported method advertised by the SMTP server. */
throw new PEAR_Exception ($method . ' is not a supported authentication method');
throw new PEAR_Exception ($method . ' authentication method cannot be called');
$object->{$method}($uid, $pwd, $authz, $this);
$func = $this->auth_methods [$method];
$func($uid, $pwd, $authz, $this);
* Add a new authentication method.
* @param string $name The authentication method name (e.g. 'PLAIN')
* @param mixed $callback The authentication callback (given as the name
* of a function or as an (object, method name)
* @param bool $prepend Should the new method be prepended to the list
* of available methods? This is the default
* behavior, giving the new method the highest
throw new InvalidArgumentException ('Method name is not a string');
throw new InvalidArgumentException ('Method callback must be string or array');
throw new InvalidArgumentException ('Bad method callback array');
* Authenticates the user using the DIGEST-MD5 method.
* @param string $uid The userid to authenticate as.
* @param string $pwd The password to authenticate with.
* @param string $authz The optional authorization proxy identifier.
$this->_put('AUTH', 'DIGEST-MD5');
/* 334: Continue authentication request */
} catch (PEAR_Exception $e) {
/* 503: Error: already authenticated */
if ($e->getCode () === 503 ) {
$auth_sasl = new Auth_SASL2 ();
$digest = $auth_sasl->factory ('digest-md5');
/* 334: Continue authentication request */
/* We don't use the protocol's third step because SMTP doesn't
* allow subsequent authentication, so we just silently ignore
/* 235: Authentication successful */
* Authenticates the user using the CRAM-MD5 method.
* @param string $uid The userid to authenticate as.
* @param string $pwd The password to authenticate with.
* @param string $authz The optional authorization proxy identifier.
$this->_put('AUTH', 'CRAM-MD5');
/* 334: Continue authentication request */
} catch (PEAR_Exception $e) {
/* 503: Error: already authenticated */
if ($e->getCode () === 503 ) {
$auth_sasl = new Auth_SASL2 ();
$cram = $auth_sasl->factory ('cram-md5');
/* 235: Authentication successful */
* Authenticates the user using the LOGIN method.
* @param string $uid The userid to authenticate as.
* @param string $pwd The password to authenticate with.
* @param string $authz The optional authorization proxy identifier.
protected function _authLogin($uid, $pwd, $authz = '')
$this->_put('AUTH', 'LOGIN');
/* 334: Continue authentication request */
} catch (PEAR_Exception $e) {
/* 503: Error: already authenticated */
if ($e->getCode () === 503 ) {
/* 334: Continue authentication request */
/* 235: Authentication successful */
* Authenticates the user using the PLAIN method.
* @param string $uid The userid to authenticate as.
* @param string $pwd The password to authenticate with.
* @param string $authz The optional authorization proxy identifier.
protected function _authPlain($uid, $pwd, $authz = '')
$this->_put('AUTH', 'PLAIN');
/* 334: Continue authentication request */
} catch (PEAR_Exception $e) {
/* 503: Error: already authenticated */
if ($e->getCode () === 503 ) {
/* 235: Authentication successful */
* @param string The domain name to say we are.
public function helo($domain)
$this->_put('HELO', $domain);
* Return the list of SMTP service extensions advertised by the server.
* @return array The list of SMTP service extensions.
* Send the MAIL FROM: command.
* @param string $sender The sender (reverse path) to set.
* @param string $params String containing additional MAIL parameters,
* such as the NOTIFY flags defined by RFC 1891
public function mailFrom($sender, $params = null )
$args = " FROM:<$sender>";
$this->_put('MAIL', $args);
* Send the RCPT TO: command.
* @param string $recipient The recipient (forward path) to add.
* @param string $params String containing additional RCPT parameters,
* such as the NOTIFY flags defined by RFC 1891.
public function rcptTo($recipient, $params = null )
$args = " TO:<$recipient>";
$this->_put('RCPT', $args);
* Quote the data so that it meets SMTP standards.
* This is provided as a separate public function to facilitate
* easier overloading for the cases where it is desirable to
* customize the quoting behavior.
* @param string &$data The message text to quote. The string must be
* passed by reference, and the text will be
/* Because a single leading period (.) signifies an end to the
* data, legitimate leading periods need to be "doubled" ('..').
* Also: change Unix (\n) and Mac (\r) linefeeds into CRLF's
array ('/^\./m', '/(?:\r\n|\n|\r(?!\n))/'),
* @param mixed $data The message data, either as a string or an open
* @param string $headers The message headers. If $headers is provided,
* $data is assumed to contain only body data.
public function data($data, $headers = null )
/* Verify that $data is a supported type. */
throw new InvalidArgumentException ('Expected a string or file resource');
/* Start by considering the size of the optional headers string. We
* also account for the addition 4 character "\r\n\r\n" separator
throw new PEAR_Exception ('Failed to get file size');
/* RFC 1870, section 3, subsection 3 states "a value of zero indicates
* that no fixed maximum message size is in force". Furthermore, it
* says that if "the parameter is omitted no information is conveyed
* about the server's fixed maximum message size". */
$limit = isset ($this->_esmtp['SIZE']) ? $this->_esmtp['SIZE'] : 0;
if ($limit > 0 && $size >= $limit) {
throw new PEAR_Exception ('Message size exceeds server limit');
/* Initiate the DATA command. */
/* If we have a separate headers string, send it first. */
$this->_send($headers . "\r\n\r\n");
/* Now we can send the message body data. */
/* Stream the contents of the file resource out over our socket
* connection, line by line. Each line must be run through the
/* If the last character is an newline, we need to grab the
* next character to check to see if it is a period. */
/* Break up the data by sending one chunk (up to 512k) at a time.
* This approach reduces our peak memory usage. */
for ($offset = 0; $offset < $size; ) {
/* Ensure we don't read beyond our data size or span multiple
* lines. quotedata() can't properly handle character data
* that's split across two line break boundaries. */
for (; $end < $size; $end++ ) {
if ($data[$end] != "\n") {
/* Extract our chunk and run it through the quoting routine. */
$chunk = substr($data, $offset, $end - $offset);
/* If we run into a problem along the way, abort. */
/* Advance the offset to the end of this chunk. */
/* Finally, send the DATA terminator sequence. */
$this->_send("\r\n.\r\n");
/* Verify that the data was successfully received by the server. */
* Send the SEND FROM: command.
* @param string $path The reverse path to send.
$this->_put('SEND', " FROM:<$path>" );
* Send the SOML FROM: command.
* @param string $path The reverse path to send.
$this->_put('SOML', " FROM:<$path>" );
* Send the SAML FROM: command.
* @param string $path The reverse path to send.
$this->_put('SAML', " FROM:<$path>" );
* @param string $string The string to verify
public function vrfy($string)
/* Note: 251 is also a valid response code */
$this->_put('VRFY', $string);
Documentation generated on Mon, 11 Mar 2019 15:57:16 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|