4 +-----------------------------------------------------------------------+
5 | program/include/rcube_smtp.inc |
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 +-----------------------------------------------------------------------+
18 $Id: rcube_smtp.inc 805 2007-09-20 13:36:57Z robin $
23 * SMTP delivery functions
28 // include required PEAR classes
29 require_once('Net/SMTP.php');
32 // define headers delimiter
33 define('SMTP_MIME_CRLF', "\r\n");
38 * Function for sending mail using SMTP.
40 * @param string Sender e-Mail address
42 * @param mixed Either a comma-seperated list of recipients
43 * (RFC822 compliant), or an array of recipients,
44 * each RFC822 valid. This may contain recipients not
45 * specified in the headers, for Bcc:, resending
48 * @param mixed The message headers to send with the mail
49 * Either as an associative array or a finally
52 * @param string The full text of the message body, including any Mime parts, etc.
54 * @return bool Returns TRUE on success, or FALSE on error
56 function smtp_mail($from, $recipients, &$headers, &$body, &$response)
58 global $SMTP_CONN, $CONFIG;
60 $smtp_host = $CONFIG['smtp_server'];
61 $smtp_port = is_numeric($CONFIG['smtp_port']) ? $CONFIG['smtp_port'] : 25;
62 $smtp_host_url = parse_url($CONFIG['smtp_server']);
65 if ($smtp_host_url['host'] && $smtp_host_url['port'])
67 $smtp_host = $smtp_host_url['host'];
68 $smtp_port = $smtp_host_url['port'];
72 if ($smtp_host_url['host'] && $smtp_host_url['scheme'])
73 $smtp_host = sprintf('%s://%s', $smtp_host_url['scheme'], $smtp_host_url['host']);
76 // create Net_SMTP object and connect to server
77 if (!is_object($smtp_conn))
79 $helo_host = empty($CONFIG['smtp_helo_host']) ? (empty($_SERVER['SERVER_NAME']) ? 'localhost' : $_SERVER['SERVER_NAME']) : $CONFIG['smtp_helo_host'];
80 $SMTP_CONN = new Net_SMTP($smtp_host, $smtp_port, $helo_host);
83 if ($CONFIG['debug_level'] & 8)
84 $SMTP_CONN->setDebug(TRUE);
87 // try to connect to server and exit on failure
88 $result = $SMTP_CONN->connect($smtp_timeout);
89 if (PEAR::isError($result))
92 $response[] = "Connection failed: ".$result->getMessage();
96 // attempt to authenticate to the SMTP server
97 if ($CONFIG['smtp_user'] && $CONFIG['smtp_pass'])
99 if (strstr($CONFIG['smtp_user'], '%u'))
100 $smtp_user = str_replace('%u', $_SESSION['username'], $CONFIG['smtp_user']);
102 $smtp_user = $CONFIG['smtp_user'];
104 if (strstr($CONFIG['smtp_pass'], '%p'))
105 $smtp_pass = str_replace('%p', decrypt_passwd($_SESSION['password']), $CONFIG['smtp_pass']);
107 $smtp_pass = $CONFIG['smtp_pass'];
109 $smtp_auth_type = empty($CONFIG['smtp_auth_type']) ? NULL : $CONFIG['smtp_auth_type'];
110 $result = $SMTP_CONN->auth($smtp_user, $smtp_pass, $smtp_auth_type);
112 if (PEAR::isError($result))
115 $response[] .= "Authentication failure: ".$result->getMessage();
122 // prepare message headers as string
123 if (is_array($headers))
125 $headerElements = smtp_prepare_headers($headers);
126 if (!$headerElements)
132 list($from, $text_headers) = $headerElements;
134 else if (is_string($headers))
135 $text_headers = $headers;
139 $response[] .= "Invalid message headers";
143 // exit if no from address is given
147 $response[] .= "No From address has been provided";
153 if (PEAR::isError($SMTP_CONN->mailFrom($from)))
156 $response[] .= "Failed to set sender '$from'";
161 // prepare list of recipients
162 $recipients = smtp_parse_rfc822($recipients);
163 if (PEAR::isError($recipients))
170 // set mail recipients
171 foreach ($recipients as $recipient)
173 if (PEAR::isError($SMTP_CONN->rcptTo($recipient)))
176 $response[] .= "Failed to add recipient '$recipient'";
182 // Concatenate headers and body so it can be passed by reference to SMTP_CONN->data
183 // so preg_replace in SMTP_CONN->quotedata will store a reference instead of a copy.
184 // We are still forced to make another copy here for a couple ticks so we don't really
185 // get to save a copy in the method call.
186 $data = $text_headers . "\r\n" . $body;
188 // unset old vars to save data and so we can pass into SMTP_CONN->data by reference.
189 unset($text_headers, $body);
191 // Send the message's headers and the body as SMTP data.
192 if (PEAR::isError($SMTP_CONN->data($data)))
195 $response[] .= "Failed to send data";
199 $response[] = join(': ', $SMTP_CONN->getResponse());
206 * Reset the global SMTP connection
209 function smtp_reset()
213 if (is_object($SMTP_CONN))
223 * Disconnect the global SMTP connection and destroy object
226 function smtp_disconnect()
230 if (is_object($SMTP_CONN))
232 $SMTP_CONN->disconnect();
239 * Take an array of mail headers and return a string containing
240 * text usable in sending a message.
242 * @param array $headers The array of headers to prepare, in an associative
243 * array, where the array key is the header name (ie,
244 * 'Subject'), and the array value is the header
245 * value (ie, 'test'). The header produced from those
246 * values would be 'Subject: test'.
248 * @return mixed Returns false if it encounters a bad address,
249 * otherwise returns an array containing two
250 * elements: Any From: address found in the headers,
251 * and the plain text version of the headers.
254 function smtp_prepare_headers($headers)
259 foreach ($headers as $key => $value)
261 if (strcasecmp($key, 'From') === 0)
263 $addresses = smtp_parse_rfc822($value);
265 if (is_array($addresses))
266 $from = $addresses[0];
268 // Reject envelope From: addresses with spaces.
269 if (strstr($from, ' '))
273 $lines[] = $key . ': ' . $value;
275 else if (strcasecmp($key, 'Received') === 0)
278 if (is_array($value))
280 foreach ($value as $line)
281 $received[] = $key . ': ' . $line;
285 $received[] = $key . ': ' . $value;
288 // Put Received: headers at the top. Spam detectors often
289 // flag messages with Received: headers after the Subject:
291 $lines = array_merge($received, $lines);
296 // If $value is an array (i.e., a list of addresses), convert
297 // it to a comma-delimited string of its elements (addresses).
298 if (is_array($value))
299 $value = implode(', ', $value);
301 $lines[] = $key . ': ' . $value;
305 return array($from, join(SMTP_MIME_CRLF, $lines) . SMTP_MIME_CRLF);
311 * Take a set of recipients and parse them, returning an array of
312 * bare addresses (forward paths) that can be passed to sendmail
313 * or an smtp server with the rcpt to: command.
315 * @param mixed Either a comma-seperated list of recipients
316 * (RFC822 compliant), or an array of recipients,
319 * @return array An array of forward paths (bare addresses).
322 function smtp_parse_rfc822($recipients)
324 // if we're passed an array, assume addresses are valid and implode them before parsing.
325 if (is_array($recipients))
326 $recipients = implode(', ', $recipients);
328 $addresses = array();
329 $recipients = smtp_explode_quoted_str(",", $recipients);
332 while (list($k, $recipient) = each($recipients))
334 $a = explode(" ", $recipient);
335 while (list($k2, $word) = each($a))
337 if ((strpos($word, "@") > 0) && (strpos($word, "\"")===false))
339 $word = ereg_replace('^<|>$', '', trim($word));
340 if (in_array($word, $addresses)===false)
341 array_push($addresses, $word);
352 function smtp_explode_quoted_str($delimiter, $string)
354 $quotes=explode("\"", $string);
355 while ( list($key, $val) = each($quotes))
357 $quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]);
358 $string=implode("\"", $quotes);
360 $result=explode($delimiter, $string);
361 while (list($key, $val) = each($result))
362 $result[$key] = str_replace("_!@!_", $delimiter, $result[$key]);