4 +-----------------------------------------------------------------------+
5 | program/include/rcube_smtp.php |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2005-2010, Roundcube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
12 | Provide SMTP functionality using socket connections |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com> |
16 +-----------------------------------------------------------------------+
18 $Id: rcube_smtp.php 4509 2011-02-09 10:51:50Z thomasb $
22 // define headers delimiter
23 define('SMTP_MIME_CRLF', "\r\n");
26 * Class to provide SMTP functionality using PEAR Net_SMTP
29 * @author Thomas Bruederli <roundcube@gmail.com>
30 * @author Aleksander Machniak <alec@alec.pl>
41 * SMTP Connection and authentication
43 * @param string Server host
44 * @param string Server port
45 * @param string User name
46 * @param string Password
48 * @return bool Returns true on success, or false on error
50 public function connect($host=null, $port=null, $user=null, $pass=null)
52 $RCMAIL = rcmail::get_instance();
54 // disconnect/destroy $this->conn
57 // reset error/response var
58 $this->error = $this->response = null;
60 // let plugins alter smtp connection config
61 $CONFIG = $RCMAIL->plugins->exec_hook('smtp_connect', array(
62 'smtp_server' => $host ? $host : $RCMAIL->config->get('smtp_server'),
63 'smtp_port' => $port ? $port : $RCMAIL->config->get('smtp_port', 25),
64 'smtp_user' => $user ? $user : $RCMAIL->config->get('smtp_user'),
65 'smtp_pass' => $pass ? $pass : $RCMAIL->config->get('smtp_pass'),
66 'smtp_auth_cid' => $RCMAIL->config->get('smtp_auth_cid'),
67 'smtp_auth_pw' => $RCMAIL->config->get('smtp_auth_pw'),
68 'smtp_auth_type' => $RCMAIL->config->get('smtp_auth_type'),
69 'smtp_helo_host' => $RCMAIL->config->get('smtp_helo_host'),
70 'smtp_timeout' => $RCMAIL->config->get('smtp_timeout'),
73 $smtp_host = rcube_parse_host($CONFIG['smtp_server']);
74 // when called from Installer it's possible to have empty $smtp_host here
75 if (!$smtp_host) $smtp_host = 'localhost';
76 $smtp_port = is_numeric($CONFIG['smtp_port']) ? $CONFIG['smtp_port'] : 25;
77 $smtp_host_url = parse_url($smtp_host);
80 if (isset($smtp_host_url['host']) && isset($smtp_host_url['port']))
82 $smtp_host = $smtp_host_url['host'];
83 $smtp_port = $smtp_host_url['port'];
87 if (isset($smtp_host_url['host']) && isset($smtp_host_url['scheme']))
88 $smtp_host = sprintf('%s://%s', $smtp_host_url['scheme'], $smtp_host_url['host']);
90 // remove TLS prefix and set flag for use in Net_SMTP::auth()
91 if (preg_match('#^tls://#i', $smtp_host)) {
92 $smtp_host = preg_replace('#^tls://#i', '', $smtp_host);
96 if (!empty($CONFIG['smtp_helo_host']))
97 $helo_host = $CONFIG['smtp_helo_host'];
98 else if (!empty($_SERVER['SERVER_NAME']))
99 $helo_host = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
101 $helo_host = 'localhost';
104 $smtp_host = rcube_idn_to_ascii($smtp_host);
106 $this->conn = new Net_SMTP($smtp_host, $smtp_port, $helo_host);
108 if($RCMAIL->config->get('smtp_debug'))
109 $this->conn->setDebug(true, array($this, 'debug_handler'));
111 // try to connect to server and exit on failure
112 $result = $this->conn->connect($smtp_timeout);
114 if (PEAR::isError($result)) {
115 $this->response[] = "Connection failed: ".$result->getMessage();
116 $this->error = array('label' => 'smtpconnerror', 'vars' => array('code' => $this->conn->_code));
121 $smtp_user = str_replace('%u', $_SESSION['username'], $CONFIG['smtp_user']);
122 $smtp_pass = str_replace('%p', $RCMAIL->decrypt($_SESSION['password']), $CONFIG['smtp_pass']);
123 $smtp_auth_type = empty($CONFIG['smtp_auth_type']) ? NULL : $CONFIG['smtp_auth_type'];
125 if (!empty($CONFIG['smtp_auth_cid'])) {
126 $smtp_authz = $smtp_user;
127 $smtp_user = $CONFIG['smtp_auth_cid'];
128 $smtp_pass = $CONFIG['smtp_auth_pw'];
131 // attempt to authenticate to the SMTP server
132 if ($smtp_user && $smtp_pass)
135 if (strpos($smtp_user, '@')) {
136 $smtp_user = rcube_idn_to_ascii($smtp_user);
139 $result = $this->conn->auth($smtp_user, $smtp_pass, $smtp_auth_type, $use_tls, $smtp_authz);
141 if (PEAR::isError($result))
143 $this->error = array('label' => 'smtpautherror', 'vars' => array('code' => $this->conn->_code));
144 $this->response[] .= 'Authentication failure: ' . $result->getMessage() . ' (Code: ' . $result->getCode() . ')';
156 * Function for sending mail
158 * @param string Sender e-Mail address
160 * @param mixed Either a comma-seperated list of recipients
161 * (RFC822 compliant), or an array of recipients,
162 * each RFC822 valid. This may contain recipients not
163 * specified in the headers, for Bcc:, resending
165 * @param mixed The message headers to send with the mail
166 * Either as an associative array or a finally
168 * @param mixed The full text of the message body, including any Mime parts
170 * @param array Delivery options (e.g. DSN request)
172 * @return bool Returns true on success, or false on error
174 public function send_mail($from, $recipients, &$headers, &$body, $opts=null)
176 if (!is_object($this->conn))
179 // prepare message headers as string
180 if (is_array($headers))
182 if (!($headerElements = $this->_prepare_headers($headers))) {
187 list($from, $text_headers) = $headerElements;
189 else if (is_string($headers))
190 $text_headers = $headers;
194 $this->response[] = "Invalid message headers";
198 // exit if no from address is given
202 $this->response[] = "No From address has been provided";
206 // RFC3461: Delivery Status Notification
208 $exts = $this->conn->getServiceExtensions();
210 if (!isset($exts['DSN'])) {
211 $this->error = array('label' => 'smtpdsnerror');
212 $this->response[] = "DSN not supported";
216 $from_params = 'RET=HDRS';
217 $recipient_params = 'NOTIFY=SUCCESS,FAILURE';
220 // RFC2298.3: remove envelope sender address
221 if (preg_match('/Content-Type: multipart\/report/', $text_headers)
222 && preg_match('/report-type=disposition-notification/', $text_headers)
228 if (PEAR::isError($this->conn->mailFrom($from, $from_params)))
230 $err = $this->conn->getResponse();
231 $this->error = array('label' => 'smtpfromerror', 'vars' => array(
232 'from' => $from, 'code' => $this->conn->_code, 'msg' => $err[1]));
233 $this->response[] = "Failed to set sender '$from'";
238 // prepare list of recipients
239 $recipients = $this->_parse_rfc822($recipients);
240 if (PEAR::isError($recipients))
242 $this->error = array('label' => 'smtprecipientserror');
247 // set mail recipients
248 foreach ($recipients as $recipient)
250 if (PEAR::isError($this->conn->rcptTo($recipient, $recipient_params))) {
251 $err = $this->conn->getResponse();
252 $this->error = array('label' => 'smtptoerror', 'vars' => array(
253 'to' => $recipient, 'code' => $this->conn->_code, 'msg' => $err[1]));
254 $this->response[] = "Failed to add recipient '$recipient'";
260 if (is_resource($body))
264 $text_headers = preg_replace('/[\r\n]+$/', '', $text_headers);
266 // Concatenate headers and body so it can be passed by reference to SMTP_CONN->data
267 // so preg_replace in SMTP_CONN->quotedata will store a reference instead of a copy.
268 // We are still forced to make another copy here for a couple ticks so we don't really
269 // get to save a copy in the method call.
270 $data = $text_headers . "\r\n" . $body;
272 // unset old vars to save data and so we can pass into SMTP_CONN->data by reference.
273 unset($text_headers, $body);
276 // Send the message's headers and the body as SMTP data.
277 if (PEAR::isError($result = $this->conn->data($data, $text_headers)))
279 $err = $this->conn->getResponse();
280 if (!in_array($err[0], array(354, 250, 221)))
281 $msg = sprintf('[%d] %s', $err[0], $err[1]);
283 $msg = $result->getMessage();
285 $this->error = array('label' => 'smtperror', 'vars' => array('msg' => $msg));
286 $this->response[] = "Failed to send data";
291 $this->response[] = join(': ', $this->conn->getResponse());
297 * Reset the global SMTP connection
300 public function reset()
302 if (is_object($this->conn))
308 * Disconnect the global SMTP connection
311 public function disconnect()
313 if (is_object($this->conn)) {
314 $this->conn->disconnect();
321 * This is our own debug handler for the SMTP connection
324 public function debug_handler(&$smtp, $message)
326 write_log('smtp', preg_replace('/\r\n$/', '', $message));
334 public function get_error()
341 * Get server response messages array
344 public function get_response()
346 return $this->response;
351 * Take an array of mail headers and return a string containing
352 * text usable in sending a message.
354 * @param array $headers The array of headers to prepare, in an associative
355 * array, where the array key is the header name (ie,
356 * 'Subject'), and the array value is the header
357 * value (ie, 'test'). The header produced from those
358 * values would be 'Subject: test'.
360 * @return mixed Returns false if it encounters a bad address,
361 * otherwise returns an array containing two
362 * elements: Any From: address found in the headers,
363 * and the plain text version of the headers.
366 private function _prepare_headers($headers)
371 foreach ($headers as $key => $value)
373 if (strcasecmp($key, 'From') === 0)
375 $addresses = $this->_parse_rfc822($value);
377 if (is_array($addresses))
378 $from = $addresses[0];
380 // Reject envelope From: addresses with spaces.
381 if (strstr($from, ' '))
384 $lines[] = $key . ': ' . $value;
386 else if (strcasecmp($key, 'Received') === 0)
389 if (is_array($value))
391 foreach ($value as $line)
392 $received[] = $key . ': ' . $line;
396 $received[] = $key . ': ' . $value;
399 // Put Received: headers at the top. Spam detectors often
400 // flag messages with Received: headers after the Subject:
402 $lines = array_merge($received, $lines);
406 // If $value is an array (i.e., a list of addresses), convert
407 // it to a comma-delimited string of its elements (addresses).
408 if (is_array($value))
409 $value = implode(', ', $value);
411 $lines[] = $key . ': ' . $value;
415 return array($from, join(SMTP_MIME_CRLF, $lines) . SMTP_MIME_CRLF);
419 * Take a set of recipients and parse them, returning an array of
420 * bare addresses (forward paths) that can be passed to sendmail
421 * or an smtp server with the rcpt to: command.
423 * @param mixed Either a comma-seperated list of recipients
424 * (RFC822 compliant), or an array of recipients,
427 * @return array An array of forward paths (bare addresses).
430 private function _parse_rfc822($recipients)
432 // if we're passed an array, assume addresses are valid and implode them before parsing.
433 if (is_array($recipients))
434 $recipients = implode(', ', $recipients);
436 $addresses = array();
437 $recipients = rcube_explode_quoted_string(',', $recipients);
440 while (list($k, $recipient) = each($recipients))
442 $a = explode(" ", $recipient);
443 while (list($k2, $word) = each($a))
445 if (strpos($word, "@") > 0 && $word[strlen($word)-1] != '"')
447 $word = preg_replace('/^<|>$/', '', trim($word));
448 if (in_array($word, $addresses)===false)
449 array_push($addresses, $word);