svncommit
2005-10-26 43fa235da354c8b53aa69ba745c1d398a758fcaf
commit | author | age
520c36 1 <?php
968bdc 2
T 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
24 require_once('Net/SMTP.php');
25
26
27 // define headers delimiter
28 define('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  */
e0ed97 52 function smtp_mail($from, $recipients, $headers, &$body)
968bdc 53   {
T 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       }
d206c1 75       
968bdc 76     // attempt to authenticate to the SMTP server
T 77     if ($CONFIG['smtp_user'] && $CONFIG['smtp_pass'])
78       {
d206c1 79       if ($CONFIG['smtp_user'] == '%u')
S 80         $smtp_user = $_SESSION['username'];
81       else
82         $smtp_user = $CONFIG['smtp_user'];
83     
84       if ($CONFIG['smtp_pass'] == '%p')
85         $smtp_pass = decrypt_passwd($_SESSION['password']);
86       else
87         $smtp_pass = $CONFIG['smtp_pass'];
88
4301b0 89       $smtp_auth_type = empty($CONFIG['smtp_auth_type']) ? NULL : $CONFIG['smtp_auth_type'];
d206c1 90           
S 91       if (PEAR::isError($SMTP_CONN->auth($smtp_user, $smtp_pass, $smtp_auth_type)))
968bdc 92         {
T 93         smtp_reset();
94         $SMTP_ERROR .= "authentication failure\n";
95         return FALSE;
96         }
97       }
98     }
99
100
101   // prepare message headers as string
102   if (is_array($headers))
103     {
104     $headerElements = smtp_prepare_headers($headers);
105     if (!$headerElements)
106       {
107       smtp_reset();
108       return FALSE;
109       }
110
111     list($from, $text_headers) = $headerElements;
112     }
113   else if (is_string($headers))
114     $text_headers = $headers;
115   else
116     {
117     smtp_reset();
118     $SMTP_ERROR .= "Invalid message headers\n";
119     return FALSE;
120     }
121
122   // exit if no from address is given
123   if (!isset($from))
124     {
125     smtp_reset();
126     $SMTP_ERROR .= "No From address has been provided\n";
127     return FALSE;
128     }
129
130
131   // set From: address
132   if (PEAR::isError($SMTP_CONN->mailFrom($from)))
133     {
134     smtp_reset();
135     $SMTP_ERROR .= "Failed to set sender '$from'\n";
136     return FALSE;
137     }
138
139
140   // prepare list of recipients
141   $recipients = smtp_parse_rfc822($recipients);
142   if (PEAR::isError($recipients))
143     {
144     smtp_reset();
145     return FALSE;
146     }
147
148
149   // set mail recipients
150   foreach ($recipients as $recipient)
151     {
152     if (PEAR::isError($SMTP_CONN->rcptTo($recipient)))
153       {
154       smtp_reset();
155       $SMTP_ERROR .= "Failed to add recipient '$recipient'\n";
156       return FALSE;
157       }
158     }
159
160
161   // Send the message's headers and the body as SMTP data.
162   if (PEAR::isError($SMTP_CONN->data("$text_headers\r\n$body")))
163     {
164     smtp_reset();
165     $SMTP_ERROR .= "Failed to send data\n";
166     return FALSE;
167     }
168
169
170   return TRUE;
171   }
172
173
174
175 /**
176  * Reset the global SMTP connection
177  * @access public
178  */
179 function smtp_reset()
180   {
181   global $SMTP_CONN;
182
183   if (is_object($SMTP_CONN))
184     {
185     $SMTP_CONN->rset();
186     smtp_disconnect();
187     }
188   }
189
190
191
192 /**
193  * Disconnect the global SMTP connection and destroy object
194  * @access public
195  */
196 function smtp_disconnect()
197   {
198   global $SMTP_CONN;
199
200   if (is_object($SMTP_CONN))
201     {
202     $SMTP_CONN->disconnect();
203     $SMTP_CONN = null;
204     }
205   }
206
207
208 /**
209  * Take an array of mail headers and return a string containing
210  * text usable in sending a message.
211  *
212  * @param array $headers The array of headers to prepare, in an associative
213  *              array, where the array key is the header name (ie,
214  *              'Subject'), and the array value is the header
215  *              value (ie, 'test'). The header produced from those
216  *              values would be 'Subject: test'.
217  *
218  * @return mixed Returns false if it encounters a bad address,
219  *               otherwise returns an array containing two
220  *               elements: Any From: address found in the headers,
221  *               and the plain text version of the headers.
222  * @access private
223  */
224 function smtp_prepare_headers($headers)
225   {
226   $lines = array();
227   $from = null;
228
229   foreach ($headers as $key => $value)
230     {
231     if (strcasecmp($key, 'From') === 0)
232       {
233       $addresses = smtp_parse_rfc822($value);
234
235       if (is_array($addresses))
236         $from = $addresses[0];
237
238       // Reject envelope From: addresses with spaces.
239       if (strstr($from, ' '))
240         return FALSE;
241
242
243       $lines[] = $key . ': ' . $value;
244       }
245     else if (strcasecmp($key, 'Received') === 0)
246       {
247       $received = array();
248       if (is_array($value))
249         {
250         foreach ($value as $line)
251           $received[] = $key . ': ' . $line;
252         }
253       else
254         {
255         $received[] = $key . ': ' . $value;
256         }
257
258       // Put Received: headers at the top.  Spam detectors often
259       // flag messages with Received: headers after the Subject:
260       // as spam.
261       $lines = array_merge($received, $lines);
262       }
263
264     else
265       {
266       // If $value is an array (i.e., a list of addresses), convert
267       // it to a comma-delimited string of its elements (addresses).
268       if (is_array($value))
269         $value = implode(', ', $value);
270
271       $lines[] = $key . ': ' . $value;
272       }
273     }
274
275   return array($from, join(SMTP_MIME_CRLF, $lines) . SMTP_MIME_CRLF);
276   }
277
278
279
280 /**
281  * Take a set of recipients and parse them, returning an array of
282  * bare addresses (forward paths) that can be passed to sendmail
283  * or an smtp server with the rcpt to: command.
284  *
285  * @param mixed Either a comma-seperated list of recipients
286  *              (RFC822 compliant), or an array of recipients,
287  *              each RFC822 valid.
288  *
289  * @return array An array of forward paths (bare addresses).
290  * @access private
291  */
292 function smtp_parse_rfc822($recipients)
293   {
294   // if we're passed an array, assume addresses are valid and implode them before parsing.
295   if (is_array($recipients))
296     $recipients = implode(', ', $recipients);
297     
298   $addresses = array();
299   $recipients = smtp_explode_quoted_str(",", $recipients);
300   
301   reset($recipients);
302   while (list($k, $recipient) = each($recipients))
303     {
304     $a = explode(" ", $recipient);
305     while (list($k2, $word) = each($a))
306       {
307       if ((strpos($word, "@") > 0) && (strpos($word, "\"")===false))
308         {
309         $word = ereg_replace('^<|>$', '', trim($word));
310         if (in_array($word, $addresses)===false)
311           array_push($addresses, $word);
312         }
313       }
314     }
315   return $addresses;
316   }
317
318
319 function smtp_explode_quoted_str($delimiter, $string)
320   {
321   $quotes=explode("\"", $string);
322   while ( list($key, $val) = each($quotes))
323     if (($key % 2) == 1) 
324       $quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]);
325     $string=implode("\"", $quotes);
326     
327     $result=explode($delimiter, $string);
328     while (list($key, $val) = each($result))
329       $result[$key] = str_replace("_!@!_", $delimiter, $result[$key]);
330
331   return $result;
332   }    
333
334
335 ?>