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

Last change on this file since 2702 was 2702, checked in by thomasb, 4 years ago

Add plugin hooks 'smtp_connect' and 'list_identities' (#1485954, #1485958)

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