3 * SMTP implementation of the PEAR Mail interface. Requires the Net_SMTP class.
9 * Copyright (c) 2010, Chuck Hagenbuch
10 * All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
16 * o Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * o Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * o The names of the authors may not be used to endorse or promote
22 * products derived from this software without specific prior written
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 * @package HTTP_Request
39 * @author Jon Parise <jon@php.net>
40 * @author Chuck Hagenbuch <chuck@horde.org>
41 * @copyright 2010 Chuck Hagenbuch
42 * @license http://opensource.org/licenses/bsd-license.php New BSD License
43 * @version CVS: $Id: smtp.php 294747 2010-02-08 08:18:33Z clockwerx $
44 * @link http://pear.php.net/package/Mail/
47 /** Error: Failed to create a Net_SMTP object */
48 define('PEAR_MAIL_SMTP_ERROR_CREATE', 10000);
50 /** Error: Failed to connect to SMTP server */
51 define('PEAR_MAIL_SMTP_ERROR_CONNECT', 10001);
53 /** Error: SMTP authentication failure */
54 define('PEAR_MAIL_SMTP_ERROR_AUTH', 10002);
56 /** Error: No From: address has been provided */
57 define('PEAR_MAIL_SMTP_ERROR_FROM', 10003);
59 /** Error: Failed to set sender */
60 define('PEAR_MAIL_SMTP_ERROR_SENDER', 10004);
62 /** Error: Failed to add recipient */
63 define('PEAR_MAIL_SMTP_ERROR_RECIPIENT', 10005);
65 /** Error: Failed to send data */
66 define('PEAR_MAIL_SMTP_ERROR_DATA', 10006);
69 * SMTP implementation of the PEAR Mail interface. Requires the Net_SMTP class.
72 * @version $Revision: 294747 $
74 class Mail_smtp extends Mail {
77 * SMTP connection object.
85 * The list of service extension parameters to pass to the Net_SMTP
89 var $_extparams = array();
92 * The SMTP host to connect to.
95 var $host = 'localhost';
98 * The port the SMTP server is on.
104 * Should SMTP authentication be used?
106 * This value may be set to true, false or the name of a specific
107 * authentication method.
109 * If the value is set to true, the Net_SMTP package will attempt to use
110 * the best authentication method advertised by the remote SMTP server.
117 * The username to use if the SMTP server requires authentication.
123 * The password to use if the SMTP server requires authentication.
129 * Hostname or domain that will be sent to the remote SMTP server in the
130 * HELO / EHLO message.
134 var $localhost = 'localhost';
137 * SMTP connection timeout value. NULL indicates no timeout.
144 * Turn on Net_SMTP debugging?
146 * @var boolean $debug
151 * Indicates whether or not the SMTP connection should persist over
152 * multiple calls to the send() method.
156 var $persist = false;
159 * Use SMTP command pipelining (specified in RFC 2920) if the SMTP server
160 * supports it. This speeds up delivery over high-latency connections. By
161 * default, use the default value supplied by Net_SMTP.
169 * Instantiates a new Mail_smtp:: object based on the parameters
170 * passed in. It looks for the following parameters:
171 * host The server to connect to. Defaults to localhost.
172 * port The port to connect to. Defaults to 25.
173 * auth SMTP authentication. Defaults to none.
174 * username The username to use for SMTP auth. No default.
175 * password The password to use for SMTP auth. No default.
176 * localhost The local hostname / domain. Defaults to localhost.
177 * timeout The SMTP connection timeout. Defaults to none.
178 * verp Whether to use VERP or not. Defaults to false.
179 * DEPRECATED as of 1.2.0 (use setMailParams()).
180 * debug Activate SMTP debug mode? Defaults to false.
181 * persist Should the SMTP connection persist?
182 * pipelining Use SMTP command pipelining
184 * If a parameter is present in the $params array, it replaces the
187 * @param array Hash containing any parameters different from the
191 function Mail_smtp($params)
193 if (isset($params['host'])) $this->host = $params['host'];
194 if (isset($params['port'])) $this->port = $params['port'];
195 if (isset($params['auth'])) $this->auth = $params['auth'];
196 if (isset($params['username'])) $this->username = $params['username'];
197 if (isset($params['password'])) $this->password = $params['password'];
198 if (isset($params['localhost'])) $this->localhost = $params['localhost'];
199 if (isset($params['timeout'])) $this->timeout = $params['timeout'];
200 if (isset($params['debug'])) $this->debug = (bool)$params['debug'];
201 if (isset($params['persist'])) $this->persist = (bool)$params['persist'];
202 if (isset($params['pipelining'])) $this->pipelining = (bool)$params['pipelining'];
204 // Deprecated options
205 if (isset($params['verp'])) {
206 $this->addServiceExtensionParameter('XVERP', is_bool($params['verp']) ? null : $params['verp']);
209 register_shutdown_function(array(&$this, '_Mail_smtp'));
213 * Destructor implementation to ensure that we disconnect from any
214 * potentially-alive persistent SMTP connections.
216 function _Mail_smtp()
222 * Implements Mail::send() function using SMTP.
224 * @param mixed $recipients Either a comma-seperated list of recipients
225 * (RFC822 compliant), or an array of recipients,
226 * each RFC822 valid. This may contain recipients not
227 * specified in the headers, for Bcc:, resending
230 * @param array $headers The array of headers to send with the mail, in an
231 * associative array, where the array key is the
232 * header name (e.g., 'Subject'), and the array value
233 * is the header value (e.g., 'test'). The header
234 * produced from those values would be 'Subject:
237 * @param string $body The full text of the message body, including any
240 * @return mixed Returns true on success, or a PEAR_Error
241 * containing a descriptive error message on
245 function send($recipients, $headers, $body)
247 /* If we don't already have an SMTP object, create one. */
248 $result = &$this->getSMTPObject();
249 if (PEAR::isError($result)) {
253 if (!is_array($headers)) {
254 return PEAR::raiseError('$headers must be an array');
257 $this->_sanitizeHeaders($headers);
259 $headerElements = $this->prepareHeaders($headers);
260 if (is_a($headerElements, 'PEAR_Error')) {
261 $this->_smtp->rset();
262 return $headerElements;
264 list($from, $textHeaders) = $headerElements;
266 /* Since few MTAs are going to allow this header to be forged
267 * unless it's in the MAIL FROM: exchange, we'll use
268 * Return-Path instead of From: if it's set. */
269 if (!empty($headers['Return-Path'])) {
270 $from = $headers['Return-Path'];
274 $this->_smtp->rset();
275 return PEAR::raiseError('No From: address has been provided',
276 PEAR_MAIL_SMTP_ERROR_FROM);
280 if (!empty($this->_extparams)) {
281 foreach ($this->_extparams as $key => $val) {
282 $params .= ' ' . $key . (is_null($val) ? '' : '=' . $val);
285 if (PEAR::isError($res = $this->_smtp->mailFrom($from, ltrim($params)))) {
286 $error = $this->_error("Failed to set sender: $from", $res);
287 $this->_smtp->rset();
288 return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_SENDER);
291 $recipients = $this->parseRecipients($recipients);
292 if (is_a($recipients, 'PEAR_Error')) {
293 $this->_smtp->rset();
297 foreach ($recipients as $recipient) {
298 $res = $this->_smtp->rcptTo($recipient);
299 if (is_a($res, 'PEAR_Error')) {
300 $error = $this->_error("Failed to add recipient: $recipient", $res);
301 $this->_smtp->rset();
302 return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_RECIPIENT);
306 /* Send the message's headers and the body as SMTP data. */
307 $res = $this->_smtp->data($textHeaders . "\r\n\r\n" . $body);
308 list(,$args) = $this->_smtp->getResponse();
310 if (preg_match("/Ok: queued as (.*)/", $args, $queued)) {
311 $this->queued_as = $queued[1];
314 /* we need the greeting; from it we can extract the authorative name of the mail server we've really connected to.
315 * ideal if we're connecting to a round-robin of relay servers and need to track which exact one took the email */
316 $this->greeting = $this->_smtp->getGreeting();
318 if (is_a($res, 'PEAR_Error')) {
319 $error = $this->_error('Failed to send data', $res);
320 $this->_smtp->rset();
321 return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_DATA);
324 /* If persistent connections are disabled, destroy our SMTP object. */
325 if ($this->persist === false) {
333 * Connect to the SMTP server by instantiating a Net_SMTP object.
335 * @return mixed Returns a reference to the Net_SMTP object on success, or
336 * a PEAR_Error containing a descriptive error message on
342 function &getSMTPObject()
344 if (is_object($this->_smtp) !== false) {
348 include_once 'Net/SMTP.php';
349 $this->_smtp = &new Net_SMTP($this->host,
353 /* If we still don't have an SMTP object at this point, fail. */
354 if (is_object($this->_smtp) === false) {
355 return PEAR::raiseError('Failed to create a Net_SMTP object',
356 PEAR_MAIL_SMTP_ERROR_CREATE);
359 /* Configure the SMTP connection. */
361 $this->_smtp->setDebug(true);
364 /* Attempt to connect to the configured SMTP server. */
365 if (PEAR::isError($res = $this->_smtp->connect($this->timeout))) {
366 $error = $this->_error('Failed to connect to ' .
367 $this->host . ':' . $this->port,
369 return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_CONNECT);
372 /* Attempt to authenticate if authentication has been enabled. */
374 $method = is_string($this->auth) ? $this->auth : '';
376 if (PEAR::isError($res = $this->_smtp->auth($this->username,
379 $error = $this->_error("$method authentication failure",
381 $this->_smtp->rset();
382 return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_AUTH);
390 * Add parameter associated with a SMTP service extension.
392 * @param string Extension keyword.
393 * @param string Any value the keyword needs.
398 function addServiceExtensionParameter($keyword, $value = null)
400 $this->_extparams[$keyword] = $value;
404 * Disconnect and destroy the current SMTP connection.
406 * @return boolean True if the SMTP connection no longer exists.
411 function disconnect()
413 /* If we have an SMTP object, disconnect and destroy it. */
414 if (is_object($this->_smtp) && $this->_smtp->disconnect()) {
418 /* We are disconnected if we no longer have an SMTP object. */
419 return ($this->_smtp === null);
423 * Build a standardized string describing the current SMTP error.
425 * @param string $text Custom string describing the error context.
426 * @param object $error Reference to the current PEAR_Error object.
428 * @return string A string describing the current SMTP error.
433 function _error($text, &$error)
435 /* Split the SMTP response into a code and a response string. */
436 list($code, $response) = $this->_smtp->getResponse();
438 /* Build our standardized error string. */
440 . ' [SMTP: ' . $error->getMessage()
441 . " (code: $code, response: $response)]";