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