4 +-----------------------------------------------------------------------+
5 | program/include/rcube_smtp.php |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2007, 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 +-----------------------------------------------------------------------+
22 // define headers delimiter
23 define('SMTP_MIME_CRLF', "\r\n");
37 function __construct()
43 * SMTP Connection and authentication
45 * @return bool Returns true on success, or false on error
47 public function connect()
49 $RCMAIL = rcmail::get_instance();
51 // disconnect/destroy $this->conn
54 // reset error/response var
55 $this->error = $this->response = null;
57 // let plugins alter smtp connection config
58 $CONFIG = $RCMAIL->plugins->exec_hook('smtp_connect', array(
59 'smtp_server' => $RCMAIL->config->get('smtp_server'),
60 'smtp_port' => $RCMAIL->config->get('smtp_port', 25),
61 'smtp_user' => $RCMAIL->config->get('smtp_user'),
62 'smtp_pass' => $RCMAIL->config->get('smtp_pass'),
63 'smtp_auth_type' => $RCMAIL->config->get('smtp_auth_type'),
64 'smtp_helo_host' => $RCMAIL->config->get('smtp_helo_host'),
65 'smtp_timeout' => $RCMAIL->config->get('smtp_timeout'),
68 $smtp_host = str_replace('%h', $_SESSION['imap_host'], $CONFIG['smtp_server']);
69 // when called from Installer it's possible to have empty $smtp_host here
70 if (!$smtp_host) $smtp_host = 'localhost';
71 $smtp_port = is_numeric($CONFIG['smtp_port']) ? $CONFIG['smtp_port'] : 25;
72 $smtp_host_url = parse_url($smtp_host);
75 if (isset($smtp_host_url['host']) && isset($smtp_host_url['port']))
77 $smtp_host = $smtp_host_url['host'];
78 $smtp_port = $smtp_host_url['port'];
82 if (isset($smtp_host_url['host']) && isset($smtp_host_url['scheme']))
83 $smtp_host = sprintf('%s://%s', $smtp_host_url['scheme'], $smtp_host_url['host']);
85 if (!empty($CONFIG['smtp_helo_host']))
86 $helo_host = $CONFIG['smtp_helo_host'];
87 else if (!empty($_SERVER['SERVER_NAME']))
88 $helo_host = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
90 $helo_host = 'localhost';
92 $this->conn = new Net_SMTP($smtp_host, $smtp_port, $helo_host);
94 if($RCMAIL->config->get('smtp_debug'))
95 $this->conn->setDebug(true, array($this, 'debug_handler'));
97 // try to connect to server and exit on failure
98 $result = $this->conn->connect($smtp_timeout);
99 if (PEAR::isError($result))
101 $this->response[] = "Connection failed: ".$result->getMessage();
102 $this->error = array('label' => 'smtpconnerror', 'vars' => array('code' => $this->conn->_code));
107 $smtp_user = str_replace('%u', $_SESSION['username'], $CONFIG['smtp_user']);
108 $smtp_pass = str_replace('%p', $RCMAIL->decrypt($_SESSION['password']), $CONFIG['smtp_pass']);
109 $smtp_auth_type = empty($CONFIG['smtp_auth_type']) ? NULL : $CONFIG['smtp_auth_type'];
111 // attempt to authenticate to the SMTP server
112 if ($smtp_user && $smtp_pass)
114 $result = $this->conn->auth($smtp_user, $smtp_pass, $smtp_auth_type);
115 if (PEAR::isError($result))
117 $this->error = array('label' => 'smtpautherror', 'vars' => array('code' => $this->conn->_code));
118 $this->response[] .= 'Authentication failure: ' . $result->getMessage() . ' (Code: ' . $result->getCode() . ')';
130 * Function for sending mail
132 * @param string Sender e-Mail address
134 * @param mixed Either a comma-seperated list of recipients
135 * (RFC822 compliant), or an array of recipients,
136 * each RFC822 valid. This may contain recipients not
137 * specified in the headers, for Bcc:, resending
140 * @param mixed The message headers to send with the mail
141 * Either as an associative array or a finally
144 * @param string The full text of the message body, including any Mime parts, etc.
146 * @return bool Returns true on success, or false on error
148 public function send_mail($from, $recipients, &$headers, &$body)
150 if (!is_object($this->conn))
153 // prepare message headers as string
154 if (is_array($headers))
156 if (!($headerElements = $this->_prepare_headers($headers))) {
161 list($from, $text_headers) = $headerElements;
163 else if (is_string($headers))
164 $text_headers = $headers;
168 $this->response[] .= "Invalid message headers";
172 // exit if no from address is given
176 $this->response[] .= "No From address has been provided";
181 if (PEAR::isError($this->conn->mailFrom($from)))
183 $this->error = array('label' => 'smtpfromerror', 'vars' => array('from' => $from, 'code' => $this->conn->_code));
184 $this->response[] .= "Failed to set sender '$from'";
189 // prepare list of recipients
190 $recipients = $this->_parse_rfc822($recipients);
191 if (PEAR::isError($recipients))
193 $this->error = array('label' => 'smtprecipientserror');
198 // set mail recipients
199 foreach ($recipients as $recipient)
201 if (PEAR::isError($this->conn->rcptTo($recipient))) {
202 $this->error = array('label' => 'smtptoerror', 'vars' => array('to' => $recipient, 'code' => $this->conn->_code));
203 $this->response[] .= "Failed to add recipient '$recipient'";
209 // Concatenate headers and body so it can be passed by reference to SMTP_CONN->data
210 // so preg_replace in SMTP_CONN->quotedata will store a reference instead of a copy.
211 // We are still forced to make another copy here for a couple ticks so we don't really
212 // get to save a copy in the method call.
213 $data = $text_headers . "\r\n" . $body;
215 // unset old vars to save data and so we can pass into SMTP_CONN->data by reference.
216 unset($text_headers, $body);
218 // Send the message's headers and the body as SMTP data.
219 if (PEAR::isError($result = $this->conn->data($data)))
221 $this->error = array('label' => 'smtperror', 'vars' => array('msg' => $result->getMessage()));
222 $this->response[] .= "Failed to send data";
227 $this->response[] = join(': ', $this->conn->getResponse());
233 * Reset the global SMTP connection
236 public function reset()
238 if (is_object($this->conn))
244 * Disconnect the global SMTP connection
247 public function disconnect()
249 if (is_object($this->conn)) {
250 $this->conn->disconnect();
257 * This is our own debug handler for the SMTP connection
260 public function debug_handler(&$smtp, $message)
262 write_log('smtp', preg_replace('/\r\n$/', '', $message));
270 public function get_error()
277 * Get server response messages array
280 public function get_response()
282 return $this->response;
287 * Take an array of mail headers and return a string containing
288 * text usable in sending a message.
290 * @param array $headers The array of headers to prepare, in an associative
291 * array, where the array key is the header name (ie,
292 * 'Subject'), and the array value is the header
293 * value (ie, 'test'). The header produced from those
294 * values would be 'Subject: test'.
296 * @return mixed Returns false if it encounters a bad address,
297 * otherwise returns an array containing two
298 * elements: Any From: address found in the headers,
299 * and the plain text version of the headers.
302 private function _prepare_headers($headers)
307 foreach ($headers as $key => $value)
309 if (strcasecmp($key, 'From') === 0)
311 $addresses = $this->_parse_rfc822($value);
313 if (is_array($addresses))
314 $from = $addresses[0];
316 // Reject envelope From: addresses with spaces.
317 if (strstr($from, ' '))
320 $lines[] = $key . ': ' . $value;
322 else if (strcasecmp($key, 'Received') === 0)
325 if (is_array($value))
327 foreach ($value as $line)
328 $received[] = $key . ': ' . $line;
332 $received[] = $key . ': ' . $value;
335 // Put Received: headers at the top. Spam detectors often
336 // flag messages with Received: headers after the Subject:
338 $lines = array_merge($received, $lines);
342 // If $value is an array (i.e., a list of addresses), convert
343 // it to a comma-delimited string of its elements (addresses).
344 if (is_array($value))
345 $value = implode(', ', $value);
347 $lines[] = $key . ': ' . $value;
351 return array($from, join(SMTP_MIME_CRLF, $lines) . SMTP_MIME_CRLF);
355 * Take a set of recipients and parse them, returning an array of
356 * bare addresses (forward paths) that can be passed to sendmail
357 * or an smtp server with the rcpt to: command.
359 * @param mixed Either a comma-seperated list of recipients
360 * (RFC822 compliant), or an array of recipients,
363 * @return array An array of forward paths (bare addresses).
366 private function _parse_rfc822($recipients)
368 // if we're passed an array, assume addresses are valid and implode them before parsing.
369 if (is_array($recipients))
370 $recipients = implode(', ', $recipients);
372 $addresses = array();
373 $recipients = rcube_explode_quoted_string(',', $recipients);
376 while (list($k, $recipient) = each($recipients))
378 $a = explode(" ", $recipient);
379 while (list($k2, $word) = each($a))
381 if ((strpos($word, "@") > 0) && (strpos($word, "\"")===false))
383 $word = preg_replace('/^<|>$/', '', trim($word));
384 if (in_array($word, $addresses)===false)
385 array_push($addresses, $word);