4 +-----------------------------------------------------------------------+
5 | program/include/rcube_smtp.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005, 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 587 2007-05-28 19:21:36Z thomasb $
23 // include required PEAR classes
24 require_once('Net/SMTP.php');
27 // define headers delimiter
28 define('SMTP_MIME_CRLF', "\r\n");
33 * Function for sending mail using SMTP.
35 * @param string Sender e-Mail address
37 * @param mixed Either a comma-seperated list of recipients
38 * (RFC822 compliant), or an array of recipients,
39 * each RFC822 valid. This may contain recipients not
40 * specified in the headers, for Bcc:, resending
43 * @param mixed The message headers to send with the mail
44 * Either as an associative array or a finally
47 * @param string The full text of the message body, including any Mime parts, etc.
49 * @return bool Returns TRUE on success, or FALSE on error
52 function smtp_mail($from, $recipients, &$headers, &$body, &$response)
54 global $SMTP_CONN, $CONFIG;
56 $smtp_host = $CONFIG['smtp_server'];
57 $smtp_port = is_numeric($CONFIG['smtp_port']) ? $CONFIG['smtp_port'] : 25;
58 $smtp_host_url = parse_url($CONFIG['smtp_server']);
61 if ($smtp_host_url['host'] && $smtp_host_url['port'])
63 $smtp_host = $smtp_host_url['host'];
64 $smtp_port = $smtp_host_url['port'];
68 if ($smtp_host_url['host'] && $smtp_host_url['scheme'])
69 $smtp_host = sprintf('%s://%s', $smtp_host_url['scheme'], $smtp_host_url['host']);
72 // create Net_SMTP object and connect to server
73 if (!is_object($smtp_conn))
75 $helo_host = !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost';
76 $SMTP_CONN = new Net_SMTP($smtp_host, $smtp_port, $helo_host);
79 if ($CONFIG['debug_level'] & 8)
80 $SMTP_CONN->setDebug(TRUE);
83 // try to connect to server and exit on failure
84 $result = $SMTP_CONN->connect($smtp_timeout);
85 if (PEAR::isError($result))
88 $response[] = "Connection failed: ".$result->getMessage();
92 // attempt to authenticate to the SMTP server
93 if ($CONFIG['smtp_user'] && $CONFIG['smtp_pass'])
95 if (strstr($CONFIG['smtp_user'], '%u'))
96 $smtp_user = str_replace('%u', $_SESSION['username'], $CONFIG['smtp_user']);
98 $smtp_user = $CONFIG['smtp_user'];
100 if (strstr($CONFIG['smtp_pass'], '%p'))
101 $smtp_pass = str_replace('%p', decrypt_passwd($_SESSION['password']), $CONFIG['smtp_pass']);
103 $smtp_pass = $CONFIG['smtp_pass'];
105 $smtp_auth_type = empty($CONFIG['smtp_auth_type']) ? NULL : $CONFIG['smtp_auth_type'];
106 $result = $SMTP_CONN->auth($smtp_user, $smtp_pass, $smtp_auth_type);
108 if (PEAR::isError($result))
111 $response[] .= "Authentication failure: ".$result->getMessage();
118 // prepare message headers as string
119 if (is_array($headers))
121 $headerElements = smtp_prepare_headers($headers);
122 if (!$headerElements)
128 list($from, $text_headers) = $headerElements;
130 else if (is_string($headers))
131 $text_headers = $headers;
135 $response[] .= "Invalid message headers";
139 // exit if no from address is given
143 $response[] .= "No From address has been provided";
149 if (PEAR::isError($SMTP_CONN->mailFrom($from)))
152 $response[] .= "Failed to set sender '$from'";
157 // prepare list of recipients
158 $recipients = smtp_parse_rfc822($recipients);
159 if (PEAR::isError($recipients))
166 // set mail recipients
167 foreach ($recipients as $recipient)
169 if (PEAR::isError($SMTP_CONN->rcptTo($recipient)))
172 $response[] .= "Failed to add recipient '$recipient'";
178 // Concatenate headers and body so it can be passed by reference to SMTP_CONN->data
179 // so preg_replace in SMTP_CONN->quotedata will store a reference instead of a copy.
180 // We are still forced to make another copy here for a couple ticks so we don't really
181 // get to save a copy in the method call.
182 $data = $text_headers . "\r\n" . $body;
184 // unset old vars to save data and so we can pass into SMTP_CONN->data by reference.
185 unset($text_headers, $body);
187 // Send the message's headers and the body as SMTP data.
188 if (PEAR::isError($SMTP_CONN->data($data)))
191 $response[] .= "Failed to send data";
195 $response[] = join(': ', $SMTP_CONN->getResponse());
202 * Reset the global SMTP connection
205 function smtp_reset()
209 if (is_object($SMTP_CONN))
219 * Disconnect the global SMTP connection and destroy object
222 function smtp_disconnect()
226 if (is_object($SMTP_CONN))
228 $SMTP_CONN->disconnect();
235 * Take an array of mail headers and return a string containing
236 * text usable in sending a message.
238 * @param array $headers The array of headers to prepare, in an associative
239 * array, where the array key is the header name (ie,
240 * 'Subject'), and the array value is the header
241 * value (ie, 'test'). The header produced from those
242 * values would be 'Subject: test'.
244 * @return mixed Returns false if it encounters a bad address,
245 * otherwise returns an array containing two
246 * elements: Any From: address found in the headers,
247 * and the plain text version of the headers.
250 function smtp_prepare_headers($headers)
255 foreach ($headers as $key => $value)
257 if (strcasecmp($key, 'From') === 0)
259 $addresses = smtp_parse_rfc822($value);
261 if (is_array($addresses))
262 $from = $addresses[0];
264 // Reject envelope From: addresses with spaces.
265 if (strstr($from, ' '))
269 $lines[] = $key . ': ' . $value;
271 else if (strcasecmp($key, 'Received') === 0)
274 if (is_array($value))
276 foreach ($value as $line)
277 $received[] = $key . ': ' . $line;
281 $received[] = $key . ': ' . $value;
284 // Put Received: headers at the top. Spam detectors often
285 // flag messages with Received: headers after the Subject:
287 $lines = array_merge($received, $lines);
292 // If $value is an array (i.e., a list of addresses), convert
293 // it to a comma-delimited string of its elements (addresses).
294 if (is_array($value))
295 $value = implode(', ', $value);
297 $lines[] = $key . ': ' . $value;
301 return array($from, join(SMTP_MIME_CRLF, $lines) . SMTP_MIME_CRLF);
307 * Take a set of recipients and parse them, returning an array of
308 * bare addresses (forward paths) that can be passed to sendmail
309 * or an smtp server with the rcpt to: command.
311 * @param mixed Either a comma-seperated list of recipients
312 * (RFC822 compliant), or an array of recipients,
315 * @return array An array of forward paths (bare addresses).
318 function smtp_parse_rfc822($recipients)
320 // if we're passed an array, assume addresses are valid and implode them before parsing.
321 if (is_array($recipients))
322 $recipients = implode(', ', $recipients);
324 $addresses = array();
325 $recipients = smtp_explode_quoted_str(",", $recipients);
328 while (list($k, $recipient) = each($recipients))
330 $a = explode(" ", $recipient);
331 while (list($k2, $word) = each($a))
333 if ((strpos($word, "@") > 0) && (strpos($word, "\"")===false))
335 $word = ereg_replace('^<|>$', '', trim($word));
336 if (in_array($word, $addresses)===false)
337 array_push($addresses, $word);
345 function smtp_explode_quoted_str($delimiter, $string)
347 $quotes=explode("\"", $string);
348 while ( list($key, $val) = each($quotes))
350 $quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]);
351 $string=implode("\"", $quotes);
353 $result=explode($delimiter, $string);
354 while (list($key, $val) = each($result))
355 $result[$key] = str_replace("_!@!_", $delimiter, $result[$key]);