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

Last change on this file since 25 was 25, checked in by roundcube, 8 years ago

Better support for Courier IMAP

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