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

Last change on this file since 2713 was 2713, checked in by alec, 4 years ago
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 10.5 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, &$error)
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      $response[] = "Connection failed: ".$result->getMessage();
100      $error = array('label' => 'smtpconnerror', 'vars' => array('code' => $SMTP_CONN->_code));
101      $SMTP_CONN = null;
102      return FALSE;
103      }
104     
105    // attempt to authenticate to the SMTP server
106    if ($CONFIG['smtp_user'] && $CONFIG['smtp_pass'])
107      {
108      if (strstr($CONFIG['smtp_user'], '%u'))
109        $smtp_user = str_replace('%u', $_SESSION['username'], $CONFIG['smtp_user']);
110      else
111        $smtp_user = $CONFIG['smtp_user'];
112
113      if (strstr($CONFIG['smtp_pass'], '%p'))
114        $smtp_pass = str_replace('%p', $RCMAIL->decrypt($_SESSION['password']), $CONFIG['smtp_pass']);
115      else
116        $smtp_pass = $CONFIG['smtp_pass'];
117
118      $smtp_auth_type = empty($CONFIG['smtp_auth_type']) ? NULL : $CONFIG['smtp_auth_type'];
119      $result = $SMTP_CONN->auth($smtp_user, $smtp_pass, $smtp_auth_type);
120   
121      if (PEAR::isError($result))
122        {
123        $error = array('label' => 'smtpautherror', 'vars' => array('code' => $SMTP_CONN->_code));
124        $response[] .= 'Authentication failure: ' . $result->getMessage() . ' (Code: ' . $result->getCode() . ')';
125        smtp_reset();
126        return FALSE;
127        }
128      }
129    }
130
131
132  // prepare message headers as string
133  if (is_array($headers))
134    {
135    $headerElements = smtp_prepare_headers($headers);
136    if (!$headerElements)
137      {
138      smtp_reset();
139      return FALSE;
140      }
141
142    list($from, $text_headers) = $headerElements;
143    }
144  else if (is_string($headers))
145    $text_headers = $headers;
146  else
147    {
148    smtp_reset();
149    $response[] .= "Invalid message headers";
150    return FALSE;
151    }
152
153  // exit if no from address is given
154  if (!isset($from))
155    {
156    smtp_reset();
157    $response[] .= "No From address has been provided";
158    return FALSE;
159    }
160
161
162  // set From: address
163  if (PEAR::isError($SMTP_CONN->mailFrom($from)))
164    {
165    $error = array('label' => 'smtpfromerror', 'vars' => array('from' => $from, 'code' => $SMTP_CONN->_code));
166    $response[] .= "Failed to set sender '$from'";
167    smtp_reset();
168    return FALSE;
169    }
170
171
172  // prepare list of recipients
173  $recipients = smtp_parse_rfc822($recipients);
174  if (PEAR::isError($recipients))
175    {
176    $error = array('label' => 'smtprecipientserror');
177    smtp_reset();
178    return FALSE;
179    }
180
181
182  // set mail recipients
183  foreach ($recipients as $recipient)
184    {
185    if (PEAR::isError($SMTP_CONN->rcptTo($recipient)))
186      {
187      $error = array('label' => 'smtptoerror', 'vars' => array('to' => $recipient, 'code' => $SMTP_CONN->_code));
188      $response[] .= "Failed to add recipient '$recipient'";
189      smtp_reset();
190      return FALSE;
191      }
192    }
193
194
195  // Concatenate headers and body so it can be passed by reference to SMTP_CONN->data
196  // so preg_replace in SMTP_CONN->quotedata will store a reference instead of a copy.
197  // We are still forced to make another copy here for a couple ticks so we don't really
198  // get to save a copy in the method call.
199  $data = $text_headers . "\r\n" . $body;
200
201  // unset old vars to save data and so we can pass into SMTP_CONN->data by reference.
202  unset($text_headers, $body);
203   
204  // Send the message's headers and the body as SMTP data.
205  if (PEAR::isError($result = $SMTP_CONN->data($data)))
206    {
207    $error = array('label' => 'smtperror', 'vars' => array('msg' => $result->getMessage()));
208    $response[] .= "Failed to send data";
209    smtp_reset();
210    return FALSE;
211    }
212
213  $response[] = join(': ', $SMTP_CONN->getResponse());
214  return TRUE;
215  }
216
217
218
219/**
220 * Reset the global SMTP connection
221 * @access public
222 */
223function smtp_reset()
224  {
225  global $SMTP_CONN;
226
227  if (is_object($SMTP_CONN) && is_resource($SMTP_CONN->_socket->fp))
228    {
229    $SMTP_CONN->rset();
230    smtp_disconnect();
231    }
232  }
233
234
235/**
236 * Disconnect the global SMTP connection and destroy object
237 * @access public
238 */
239function smtp_disconnect()
240  {
241  global $SMTP_CONN;
242
243  if (is_object($SMTP_CONN))
244    {
245    $SMTP_CONN->disconnect();
246    $SMTP_CONN = null;
247    }
248  }
249
250
251/**
252 * Take an array of mail headers and return a string containing
253 * text usable in sending a message.
254 *
255 * @param array $headers The array of headers to prepare, in an associative
256 *              array, where the array key is the header name (ie,
257 *              'Subject'), and the array value is the header
258 *              value (ie, 'test'). The header produced from those
259 *              values would be 'Subject: test'.
260 *
261 * @return mixed Returns false if it encounters a bad address,
262 *               otherwise returns an array containing two
263 *               elements: Any From: address found in the headers,
264 *               and the plain text version of the headers.
265 * @access private
266 */
267function smtp_prepare_headers($headers)
268  {
269  $lines = array();
270  $from = null;
271
272  foreach ($headers as $key => $value)
273    {
274    if (strcasecmp($key, 'From') === 0)
275      {
276      $addresses = smtp_parse_rfc822($value);
277
278      if (is_array($addresses))
279        $from = $addresses[0];
280
281      // Reject envelope From: addresses with spaces.
282      if (strstr($from, ' '))
283        return FALSE;
284
285
286      $lines[] = $key . ': ' . $value;
287      }
288    else if (strcasecmp($key, 'Received') === 0)
289      {
290      $received = array();
291      if (is_array($value))
292        {
293        foreach ($value as $line)
294          $received[] = $key . ': ' . $line;
295        }
296      else
297        {
298        $received[] = $key . ': ' . $value;
299        }
300
301      // Put Received: headers at the top.  Spam detectors often
302      // flag messages with Received: headers after the Subject:
303      // as spam.
304      $lines = array_merge($received, $lines);
305      }
306
307    else
308      {
309      // If $value is an array (i.e., a list of addresses), convert
310      // it to a comma-delimited string of its elements (addresses).
311      if (is_array($value))
312        $value = implode(', ', $value);
313
314      $lines[] = $key . ': ' . $value;
315      }
316    }
317
318  return array($from, join(SMTP_MIME_CRLF, $lines) . SMTP_MIME_CRLF);
319  }
320
321
322
323/**
324 * Take a set of recipients and parse them, returning an array of
325 * bare addresses (forward paths) that can be passed to sendmail
326 * or an smtp server with the rcpt to: command.
327 *
328 * @param mixed Either a comma-seperated list of recipients
329 *              (RFC822 compliant), or an array of recipients,
330 *              each RFC822 valid.
331 *
332 * @return array An array of forward paths (bare addresses).
333 * @access private
334 */
335function smtp_parse_rfc822($recipients)
336  {
337  // if we're passed an array, assume addresses are valid and implode them before parsing.
338  if (is_array($recipients))
339    $recipients = implode(', ', $recipients);
340   
341  $addresses = array();
342  $recipients = rcube_explode_quoted_string(',', $recipients);
343 
344  reset($recipients);
345  while (list($k, $recipient) = each($recipients))
346    {
347  $a = explode(" ", $recipient);
348  while (list($k2, $word) = each($a))
349    {
350      if ((strpos($word, "@") > 0) && (strpos($word, "\"")===false))
351        {
352        $word = preg_replace('/^<|>$/', '', trim($word));
353        if (in_array($word, $addresses)===false)
354          array_push($addresses, $word);
355        }
356      }
357    }
358  return $addresses;
359  }
360
361?>
Note: See TracBrowser for help on using the repository browser.