4 ** This contains all the functions needed to send messages through
5 ** an smtp server or sendmail.
10 if (defined('smtp_php'))
12 define('smtp_php', true);
14 include('../functions/addressbook.php');
16 global $username, $popuser, $domain;
18 // This should most probably go to some initialization...
19 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
20 $popuser = $usernamedata[1];
21 $domain = $usernamedata[2];
26 // We need domain for smtp
28 $domain = getenv('HOSTNAME');
30 // Returns true only if this message is multipart
31 function isMultipart () {
34 if (count($attachments)>0)
40 // looks up aliases in the addressbook and expands them to
42 // Adds @$domain if it wasn't in the address book and if it
43 // doesn't have an @ symbol in it
44 function expandAddrs ($array) {
47 $abook = addressbook_init();
48 for ($i=0; $i < count($array); $i++
) {
49 $result = $abook->lookup($array[$i]);
51 if (isset($result['email'])) {
52 if (isset($result['name'])) {
53 $ret = '"'.$result['name'].'" ';
55 $ret .= '<'.$result['email'].'>';
60 $array[$i] = '<' . $array[$i] . '>';
63 if (strpos($array[$i], '@') === false) {
64 $array[$i] .= '@' . $domain;
70 // Attach the files that are due to be attached
71 function attachFiles ($fp) {
72 global $attachments, $attachment_dir;
77 foreach ($attachments as $info)
79 if (isset($info['type']))
80 $filetype = $info['type'];
82 $filetype = 'application/octet-stream';
84 $header = '--'.mimeBoundary()."\r\n";
85 $header .= "Content-Type: $filetype; name=\"" .
86 $info['remotefilename'] . "\"\r\n";
87 $header .= "Content-Disposition: attachment; filename=\"" .
88 $info['remotefilename'] . "\"\r\n";
89 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
91 $length +
= strlen($header);
93 $file = fopen ($attachment_dir . $info['localfilename'], 'r');
94 while ($tmp = fread($file, 570)) {
95 $encoded = chunk_split(base64_encode($tmp));
96 $length +
= strlen($encoded);
97 fputs ($fp, $encoded);
106 // Delete files that are uploaded for attaching
107 function deleteAttachments() {
108 global $attachments, $attachment_dir;
112 while (list($localname, $remotename) = each($attachments)) {
113 if (!ereg ("\\/", $localname)) {
114 unlink ($attachment_dir.$localname);
115 unlink ($attachment_dir.$localname.'.info');
121 // Return a nice MIME-boundary
122 function mimeBoundary () {
123 static $mimeBoundaryString;
125 if ($mimeBoundaryString == "") {
126 $mimeBoundaryString = "----=_" .
127 GenerateRandomString(60, '\'()+,-./:=?_', 7);
130 return $mimeBoundaryString;
133 /* Time offset for correct timezone */
134 function timezone () {
137 $diff_second = date('Z');
139 $diff_second = - $diff_second;
140 if ($diff_second > 0)
145 $diff_second = abs($diff_second);
147 $diff_hour = floor ($diff_second / 3600);
148 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
150 $zonename = '('.strftime('%Z').')';
151 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
155 /* Print all the needed RFC822 headers */
156 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
157 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
158 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
159 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
162 // Storing the header to make sure the header is the same
163 // everytime the header is printed.
164 static $header, $headerlength;
167 $to = expandAddrs(parseAddrs($t));
168 $cc = expandAddrs(parseAddrs($c));
169 $bcc = expandAddrs(parseAddrs($b));
170 $reply_to = getPref($data_dir, $username, 'reply_to');
171 $from = getPref($data_dir, $username, 'full_name');
172 $from_addr = getPref($data_dir, $username, 'email_address');
174 if ($from_addr == '')
175 $from_addr = $popuser.'@'.$domain;
177 $to_list = getLineOfAddrs($to);
178 $cc_list = getLineOfAddrs($cc);
179 $bcc_list = getLineOfAddrs($bcc);
181 /* Encoding 8-bit characters and making from line */
182 $subject = encodeHeader($subject);
184 $from = "<$from_addr>";
186 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
188 /* This creates an RFC 822 date */
189 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
191 /* Create a message-id */
192 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
193 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
195 /* Make an RFC822 Received: line */
196 if (isset($REMOTE_HOST))
197 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
199 $received_from = $REMOTE_ADDR;
201 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
202 if ($HTTP_X_FORWARDED_FOR == '')
203 $HTTP_X_FORWARDED_FOR = 'unknown';
204 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
207 $header = "Received: from $received_from\r\n";
208 $header .= " (SquirrelMail authenticated user $username)\r\n";
209 $header .= " by $SERVER_NAME with HTTP;\r\n";
210 $header .= " $date\r\n";
212 /* Insert the rest of the header fields */
213 $header .= "Message-ID: $message_id\r\n";
214 $header .= "Date: $date\r\n";
215 $header .= "Subject: $subject\r\n";
216 $header .= "From: $from\r\n";
217 $header .= "To: $to_list\r\n"; // Who it's TO
219 /* Insert headers from the $more_headers array */
220 if(is_array($more_headers)) {
221 reset($more_headers);
222 while(list($h_name, $h_val) = each($more_headers)) {
223 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
228 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
232 $header .= "Reply-To: $reply_to\r\n";
236 // BCCs is removed from header by sendmail
237 $header .= "Bcc: $bcc_list\r\n";
241 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
244 $header .= "MIME-Version: 1.0\r\n";
247 $header .= 'Content-Type: multipart/mixed; boundary="';
248 $header .= mimeBoundary();
251 if ($default_charset != '')
252 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
254 $header .= "Content-Type: text/plain;\r\n";
255 $header .= "Content-Transfer-Encoding: 8bit\r\n";
257 $header .= "\r\n"; // One blank line to separate header and body
259 $headerlength = strlen($header);
263 fputs ($fp, $header);
265 return $headerlength;
269 function writeBody ($fp, $passedBody) {
270 global $default_charset;
272 $attachmentlength = 0;
275 $body = '--'.mimeBoundary()."\r\n";
277 if ($default_charset != "")
278 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
280 $body .= "Content-Type: text/plain\r\n";
282 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
283 $body .= $passedBody . "\r\n\r\n";
286 $attachmentlength = attachFiles($fp);
288 if (!isset($postbody)) $postbody = "";
289 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
290 fputs ($fp, $postbody);
292 $body = $passedBody . "\r\n";
295 fputs ($fp, $postbody);
298 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
301 // Send mail using the sendmail command
302 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
303 global $sendmail_path, $popuser, $username, $domain;
305 // Build envelope sender address. Make sure it doesn't contain
306 // spaces or other "weird" chars that would allow a user to
307 // exploit the shell/pipe it is used in.
308 $envelopefrom = "$popuser@$domain";
309 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
310 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
311 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
313 // open pipe to sendmail
314 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), 'w');
316 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
317 $bodylength = writeBody($fp, $body);
321 return ($headerlength +
$bodylength);
324 function smtpReadData($smtpConnection) {
325 $read = fgets($smtpConnection, 1024);
329 $data[$counter] = $read;
330 $read = fgets($smtpConnection, 1024);
335 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
336 global $username, $popuser, $domain, $version, $smtpServerAddress, $smtpPort,
337 $data_dir, $color, $use_authenticated_smtp;
339 $to = expandAddrs(parseAddrs($t));
340 $cc = expandAddrs(parseAddrs($c));
341 $bcc = expandAddrs(parseAddrs($b));
342 $from_addr = getPref($data_dir, $username, 'email_address');
345 $from_addr = "$popuser@$domain";
347 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
348 if (!$smtpConnection) {
349 echo 'Error connecting to SMTP Server.<br>';
350 echo "$errorNumber : $errorString<br>";
353 $tmp = fgets($smtpConnection, 1024);
354 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
356 $to_list = getLineOfAddrs($to);
357 $cc_list = getLineOfAddrs($cc);
359 /** Lets introduce ourselves */
360 if (! isset ($use_authenticated_smtp) ||
$use_authenticated_smtp == false) {
361 fputs($smtpConnection, "HELO $domain\r\n");
362 $tmp = fgets($smtpConnection, 1024);
363 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
365 fputs($smtpConnection, "EHLO $domain\r\n");
366 $tmp = fgets($smtpConnection, 1024);
367 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
369 fputs($smtpConnection, "AUTH LOGIN\r\n");
370 $tmp = fgets($smtpConnection, 1024);
371 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
373 fputs($smtpConnection, base64_encode ($username) . "\r\n");
374 $tmp = fgets($smtpConnection, 1024);
375 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
377 fputs($smtpConnection, base64_encode ($OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
378 $tmp = fgets($smtpConnection, 1024);
379 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
382 /** Ok, who is sending the message? */
383 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
384 $tmp = fgets($smtpConnection, 1024);
385 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
387 /** send who the recipients are */
388 for ($i = 0; $i < count($to); $i++
) {
389 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
390 $tmp = fgets($smtpConnection, 1024);
391 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
393 for ($i = 0; $i < count($cc); $i++
) {
394 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
395 $tmp = fgets($smtpConnection, 1024);
396 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
398 for ($i = 0; $i < count($bcc); $i++
) {
399 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
400 $tmp = fgets($smtpConnection, 1024);
401 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
404 /** Lets start sending the actual message */
405 fputs($smtpConnection, "DATA\r\n");
406 $tmp = fgets($smtpConnection, 1024);
407 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
410 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
411 $bodylength = writeBody($smtpConnection, $body);
413 fputs($smtpConnection, ".\r\n"); // end the DATA part
414 $tmp = fgets($smtpConnection, 1024);
415 $num = errorCheck($tmp, $smtpConnection, true);
417 $tmp = nl2br(htmlspecialchars($tmp));
418 displayPageHeader($color, 'None');
419 include ("../functions/display_messages.php");
420 $msg = "Message not sent!<br>\nReason given: $tmp";
421 plain_error_message($msg, $color);
425 fputs($smtpConnection, "QUIT\r\n"); // log off
427 fclose($smtpConnection);
429 return ($headerlength +
$bodylength);
433 function errorCheck($line, $smtpConnection, $verbose = false) {
435 include '../functions/page_header.php';
437 // Read new lines on a multiline response
439 while(ereg("^[0-9]+-", $line)) {
440 $line = fgets($smtpConnection, 1024);
447 $err_num = substr($line, 0, strpos($line, " "));
449 case 500: $message = 'Syntax error; command not recognized';
452 case 501: $message = 'Syntax error in parameters or arguments';
455 case 502: $message = 'Command not implemented';
458 case 503: $message = 'Bad sequence of commands';
461 case 504: $message = 'Command parameter not implemented';
466 case 211: $message = 'System status, or system help reply';
469 case 214: $message = 'Help message';
474 case 220: $message = 'Service ready';
477 case 221: $message = 'Service closing transmission channel';
480 case 421: $message = 'Service not available, closing chanel';
484 case 235: return(5); break;
485 case 250: $message = 'Requested mail action okay, completed';
488 case 251: $message = 'User not local; will forward';
491 case 334: return(5); break;
492 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
495 case 550: $message = 'Requested action not taken: mailbox unavailable';
498 case 451: $message = 'Requested action aborted: error in processing';
501 case 551: $message = 'User not local; please try forwarding';
504 case 452: $message = 'Requested action not taken: insufficient system storage';
507 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
510 case 553: $message = 'Requested action not taken: mailbox name not allowed';
513 case 354: $message = 'Start mail input; end with .';
516 case 554: $message = 'Transaction failed';
519 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
526 displayPageHeader($color, 'None');
527 include ("../functions/display_messages.php");
528 $lines = nl2br(htmlspecialchars($lines));
529 $msg = $message . "<br>\nServer replied: $lines";
530 plain_error_message($msg, $color);
532 if (! $verbose) return $status;
536 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
537 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad;
538 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
539 $more_headers = Array();
541 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
543 if (isset($reply_id) && $reply_id) {
544 sqimap_mailbox_select ($imap_stream, $mailbox);
545 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
547 // Insert In-Reply-To and References headers if the
548 // message-id of the message we reply to is set (longer than "<>")
549 // The References header should really be the old Referenced header
550 // with the message ID appended, but it can be only the message ID too.
551 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
552 if(strlen($hdr->message_id
) > 2) {
553 $more_headers['In-Reply-To'] = $hdr->message_id
;
554 $more_headers['References'] = $hdr->message_id
;
558 // In order to remove the problem of users not able to create
559 // messages with "." on a blank line, RFC821 has made provision
560 // in section 4.5.2 (Transparency).
561 $body = ereg_replace("\n\\.", "\n..", $body);
562 $body = ereg_replace("^\\.", "..", $body);
564 // this is to catch all plain \n instances and
565 // replace them with \r\n.
566 $body = ereg_replace("\r\n", "\n", $body);
567 $body = ereg_replace("\n", "\r\n", $body);
570 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
572 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
575 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
576 sqimap_append ($imap_stream, $sent_folder, $length);
577 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
578 writeBody ($imap_stream, $body);
579 sqimap_append_done ($imap_stream);
581 sqimap_logout($imap_stream);
582 // Delete the files uploaded for attaching (if any).
583 // only if $length != 0 (if there was no error)