source: subversion/trunk/roundcubemail/program/include/rcube_smtp.inc @ 2491

Last change on this file since 2491 was 2491, checked in by alec, 4 years ago
  • Added possibility to encrypt received header, option 'http_received_header_encrypt', added some more logic in encrypt/decrypt functions for security
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 9.4 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcube_smtp.inc                                        |
6 |                                                                       |
7 | This file is part of the RoundCube Webmail client                     |
8 | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland                 |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   Provide SMTP functionality using socket connections                 |
13 |                                                                       |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16 +-----------------------------------------------------------------------+
17
18 $Id$
19
20*/
21
22/**
23 * SMTP delivery functions
24 *
25 * @package Mail
26 */
27
28// include required PEAR classes
29require_once('Net/SMTP.php');
30
31
32// define headers delimiter
33define('SMTP_MIME_CRLF', "\r\n");
34
35$SMTP_CONN = null;
36
37/**
38 * Function for sending mail using SMTP.
39 *
40 * @param string Sender e-Mail address
41 *
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
46 *               messages, etc.
47 *
48 * @param mixed  The message headers to send with the mail
49 *               Either as an associative array or a finally
50 *               formatted string
51 *
52 * @param string The full text of the message body, including any Mime parts, etc.
53 *
54 * @return bool  Returns TRUE on success, or FALSE on error
55 */
56function smtp_mail($from, $recipients, &$headers, &$body, &$response)
57  {
58  global $SMTP_CONN, $CONFIG, $RCMAIL;
59  $smtp_timeout = null;
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']);
63 
64  // overwrite port
65  if (isset($smtp_host_url['host']) && isset($smtp_host_url['port']))
66    {
67    $smtp_host = $smtp_host_url['host'];
68    $smtp_port = $smtp_host_url['port'];
69    }
70
71  // re-write smtp host
72  if (isset($smtp_host_url['host']) && isset($smtp_host_url['scheme']))
73    $smtp_host = sprintf('%s://%s', $smtp_host_url['scheme'], $smtp_host_url['host']);
74
75
76  // create Net_SMTP object and connect to server
77  if (!is_object($SMTP_CONN))
78    {
79    if (!empty($CONFIG['smtp_helo_host']))
80      $helo_host = $CONFIG['smtp_helo_host'];
81    else if (!empty($_SERVER['SERVER_NAME']))
82      $helo_host = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
83    else
84      $helo_host = 'localhost';
85
86    $SMTP_CONN = new Net_SMTP($smtp_host, $smtp_port, $helo_host);
87
88    // try to connect to server and exit on failure
89    $result = $SMTP_CONN->connect($smtp_timeout);
90    if (PEAR::isError($result))
91      {
92      $SMTP_CONN = null;
93      $response[] = "Connection failed: ".$result->getMessage();
94      return FALSE;
95      }
96     
97    // attempt to authenticate to the SMTP server
98    if ($CONFIG['smtp_user'] && $CONFIG['smtp_pass'])
99      {
100      if (strstr($CONFIG['smtp_user'], '%u'))
101        $smtp_user = str_replace('%u', $_SESSION['username'], $CONFIG['smtp_user']);
102      else
103        $smtp_user = $CONFIG['smtp_user'];
104
105      if (strstr($CONFIG['smtp_pass'], '%p'))
106        $smtp_pass = str_replace('%p', $RCMAIL->decrypt($_SESSION['password']), $CONFIG['smtp_pass']);
107      else
108        $smtp_pass = $CONFIG['smtp_pass'];
109
110      $smtp_auth_type = empty($CONFIG['smtp_auth_type']) ? NULL : $CONFIG['smtp_auth_type'];
111      $result = $SMTP_CONN->auth($smtp_user, $smtp_pass, $smtp_auth_type);
112   
113      if (PEAR::isError($result))
114        {
115        smtp_reset();
116        $response[] .= 'Authentication failure: ' . $result->getMessage() . ' (Code: ' . $result->getCode() . ')';
117        return FALSE;
118        }
119      }
120    }
121
122
123  // prepare message headers as string
124  if (is_array($headers))
125    {
126    $headerElements = smtp_prepare_headers($headers);
127    if (!$headerElements)
128      {
129      smtp_reset();
130      return FALSE;
131      }
132
133    list($from, $text_headers) = $headerElements;
134    }
135  else if (is_string($headers))
136    $text_headers = $headers;
137  else
138    {
139    smtp_reset();
140    $response[] .= "Invalid message headers";
141    return FALSE;
142    }
143
144  // exit if no from address is given
145  if (!isset($from))
146    {
147    smtp_reset();
148    $response[] .= "No From address has been provided";
149    return FALSE;
150    }
151
152
153  // set From: address
154  if (PEAR::isError($SMTP_CONN->mailFrom($from)))
155    {
156    smtp_reset();
157    $response[] .= "Failed to set sender '$from'";
158    return FALSE;
159    }
160
161
162  // prepare list of recipients
163  $recipients = smtp_parse_rfc822($recipients);
164  if (PEAR::isError($recipients))
165    {
166    smtp_reset();
167    return FALSE;
168    }
169
170
171  // set mail recipients
172  foreach ($recipients as $recipient)
173    {
174    if (PEAR::isError($SMTP_CONN->rcptTo($recipient)))
175      {
176      smtp_reset();
177      $response[] .= "Failed to add recipient '$recipient'";
178      return FALSE;
179      }
180    }
181
182
183  // Concatenate headers and body so it can be passed by reference to SMTP_CONN->data
184  // so preg_replace in SMTP_CONN->quotedata will store a reference instead of a copy.
185  // We are still forced to make another copy here for a couple ticks so we don't really
186  // get to save a copy in the method call.
187  $data = $text_headers . "\r\n" . $body;
188
189  // unset old vars to save data and so we can pass into SMTP_CONN->data by reference.
190  unset($text_headers, $body);
191   
192  // Send the message's headers and the body as SMTP data.
193  if (PEAR::isError($SMTP_CONN->data($data)))
194    {
195    smtp_reset();
196    $response[] .= "Failed to send data";
197    return FALSE;
198    }
199
200  $response[] = join(': ', $SMTP_CONN->getResponse());
201  return TRUE;
202  }
203
204
205
206/**
207 * Reset the global SMTP connection
208 * @access public
209 */
210function smtp_reset()
211  {
212  global $SMTP_CONN;
213
214  if (is_object($SMTP_CONN))
215    {
216    $SMTP_CONN->rset();
217    smtp_disconnect();
218    }
219  }
220
221
222
223/**
224 * Disconnect the global SMTP connection and destroy object
225 * @access public
226 */
227function smtp_disconnect()
228  {
229  global $SMTP_CONN;
230
231  if (is_object($SMTP_CONN))
232    {
233    $SMTP_CONN->disconnect();
234    $SMTP_CONN = null;
235    }
236  }
237
238
239/**
240 * Take an array of mail headers and return a string containing
241 * text usable in sending a message.
242 *
243 * @param array $headers The array of headers to prepare, in an associative
244 *              array, where the array key is the header name (ie,
245 *              'Subject'), and the array value is the header
246 *              value (ie, 'test'). The header produced from those
247 *              values would be 'Subject: test'.
248 *
249 * @return mixed Returns false if it encounters a bad address,
250 *               otherwise returns an array containing two
251 *               elements: Any From: address found in the headers,
252 *               and the plain text version of the headers.
253 * @access private
254 */
255function smtp_prepare_headers($headers)
256  {
257  $lines = array();
258  $from = null;
259
260  foreach ($headers as $key => $value)
261    {
262    if (strcasecmp($key, 'From') === 0)
263      {
264      $addresses = smtp_parse_rfc822($value);
265
266      if (is_array($addresses))
267        $from = $addresses[0];
268
269      // Reject envelope From: addresses with spaces.
270      if (strstr($from, ' '))
271        return FALSE;
272
273
274      $lines[] = $key . ': ' . $value;
275      }
276    else if (strcasecmp($key, 'Received') === 0)
277      {
278      $received = array();
279      if (is_array($value))
280        {
281        foreach ($value as $line)
282          $received[] = $key . ': ' . $line;
283        }
284      else
285        {
286        $received[] = $key . ': ' . $value;
287        }
288
289      // Put Received: headers at the top.  Spam detectors often
290      // flag messages with Received: headers after the Subject:
291      // as spam.
292      $lines = array_merge($received, $lines);
293      }
294
295    else
296      {
297      // If $value is an array (i.e., a list of addresses), convert
298      // it to a comma-delimited string of its elements (addresses).
299      if (is_array($value))
300        $value = implode(', ', $value);
301
302      $lines[] = $key . ': ' . $value;
303      }
304    }
305
306  return array($from, join(SMTP_MIME_CRLF, $lines) . SMTP_MIME_CRLF);
307  }
308
309
310
311/**
312 * Take a set of recipients and parse them, returning an array of
313 * bare addresses (forward paths) that can be passed to sendmail
314 * or an smtp server with the rcpt to: command.
315 *
316 * @param mixed Either a comma-seperated list of recipients
317 *              (RFC822 compliant), or an array of recipients,
318 *              each RFC822 valid.
319 *
320 * @return array An array of forward paths (bare addresses).
321 * @access private
322 */
323function smtp_parse_rfc822($recipients)
324  {
325  // if we're passed an array, assume addresses are valid and implode them before parsing.
326  if (is_array($recipients))
327    $recipients = implode(', ', $recipients);
328   
329  $addresses = array();
330  $recipients = rcube_explode_quoted_string(',', $recipients);
331 
332  reset($recipients);
333  while (list($k, $recipient) = each($recipients))
334    {
335  $a = explode(" ", $recipient);
336  while (list($k2, $word) = each($a))
337    {
338      if ((strpos($word, "@") > 0) && (strpos($word, "\"")===false))
339        {
340        $word = preg_replace('/^<|>$/', '', trim($word));
341        if (in_array($word, $addresses)===false)
342          array_push($addresses, $word);
343        }
344      }
345    }
346  return $addresses;
347  }
348
349?>
Note: See TracBrowser for help on using the repository browser.