6 * Copyright (c) 1999-2001 The Squirrelmail Development Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This contains all the functions needed to send messages through
10 * an smtp server or sendmail.
15 require_once('../functions/addressbook.php');
16 require_once('../functions/plugin.php');
18 global $username, $popuser, $domain;
20 // This should most probably go to some initialization...
21 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
22 $popuser = $usernamedata[1];
23 $domain = $usernamedata[2];
28 // We need domain for smtp
30 $domain = getenv('HOSTNAME');
32 // Returns true only if this message is multipart
33 function isMultipart () {
36 if (count($attachments)>0)
42 // looks up aliases in the addressbook and expands them to
44 // Adds @$domain if it wasn't in the address book and if it
45 // doesn't have an @ symbol in it
46 function expandAddrs ($array) {
49 // don't show errors -- kinda critical that we don't see
50 // them here since the redirect won't work if we do show them
51 $abook = addressbook_init(false);
52 for ($i=0; $i < count($array); $i++
) {
53 $result = $abook->lookup($array[$i]);
55 if (isset($result['email'])) {
56 if (isset($result['name'])) {
57 $ret = '"'.$result['name'].'" ';
59 $ret .= '<'.$result['email'].'>';
64 if (strpos($array[$i], '@') === false)
65 $array[$i] .= '@' . $domain;
66 $array[$i] = '<' . $array[$i] . '>';
73 // looks up aliases in the addressbook and expands them to
74 // the RFC 821 valid RCPT address. ie <user@example.com>
75 // Adds @$domain if it wasn't in the address book and if it
76 // doesn't have an @ symbol in it
77 function expandRcptAddrs ($array) {
80 // don't show errors -- kinda critical that we don't see
81 // them here since the redirect won't work if we do show them
82 $abook = addressbook_init(false);
83 for ($i=0; $i < count($array); $i++
) {
84 $result = $abook->lookup($array[$i]);
86 if (isset($result['email'])) {
87 $ret = '<'.$result['email'].'>';
92 if (strpos($array[$i], '@') === false)
93 $array[$i] .= '@' . $domain;
94 $array[$i] = '<' . $array[$i] . '>';
101 // Attach the files that are due to be attached
102 function attachFiles ($fp) {
103 global $attachments, $attachment_dir;
108 foreach ($attachments as $info)
110 if (isset($info['type']))
111 $filetype = $info['type'];
113 $filetype = 'application/octet-stream';
115 $header = '--'.mimeBoundary()."\r\n";
116 $header .= "Content-Type: $filetype; name=\"" .
117 $info['remotefilename'] . "\"\r\n";
118 $header .= "Content-Disposition: attachment; filename=\"" .
119 $info['remotefilename'] . "\"\r\n";
121 // Use 'rb' for NT systems -- read binary
122 // Unix doesn't care -- everything's binary! :-)
123 $file = fopen ($attachment_dir . $info['localfilename'], 'rb');
124 if (substr($filetype, 0, 5) == 'text/' ||
125 $filetype == 'message/rfc822') {
127 fputs ($fp, $header);
128 $length +
= strlen($header);
129 while ($tmp = fgets($file, 4096)) {
130 $tmp = str_replace("\r\n", "\n", $tmp);
131 $tmp = str_replace("\r", "\n", $tmp);
132 $tmp = str_replace("\n", "\r\n", $tmp);
133 if (feof($fp) && substr($tmp, -2) != "\r\n")
136 $length +
= strlen($tmp);
139 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
140 fputs ($fp, $header);
141 $length +
= strlen($header);
142 while ($tmp = fread($file, 570)) {
143 $encoded = chunk_split(base64_encode($tmp));
144 $length +
= strlen($encoded);
145 fputs ($fp, $encoded);
155 // Delete files that are uploaded for attaching
156 function deleteAttachments() {
157 global $attachments, $attachment_dir;
161 while (list($localname, $remotename) = each($attachments)) {
162 if (!ereg ("\\/", $localname)) {
163 unlink ($attachment_dir.$localname);
164 unlink ($attachment_dir.$localname.'.info');
170 // Return a nice MIME-boundary
171 function mimeBoundary () {
172 static $mimeBoundaryString;
174 if ($mimeBoundaryString == "") {
175 $mimeBoundaryString = "----=_" .
176 GenerateRandomString(60, '\'()+,-./:=?_', 7);
179 return $mimeBoundaryString;
182 /* Time offset for correct timezone */
183 function timezone () {
186 $diff_second = date('Z');
188 $diff_second = - $diff_second;
189 if ($diff_second > 0)
194 $diff_second = abs($diff_second);
196 $diff_hour = floor ($diff_second / 3600);
197 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
199 $zonename = '('.strftime('%Z').')';
200 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
204 /* Print all the needed RFC822 headers */
205 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
206 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
207 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
208 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
209 global $REMOTE_HOST, $identity;
211 // Storing the header to make sure the header is the same
212 // everytime the header is printed.
213 static $header, $headerlength;
216 $to = expandAddrs(parseAddrs($t));
217 $cc = expandAddrs(parseAddrs($c));
218 $bcc = expandAddrs(parseAddrs($b));
219 if (isset($identity) && $identity != 'default')
221 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
222 $from = getPref($data_dir, $username, 'full_name' . $identity);
223 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
227 $reply_to = getPref($data_dir, $username, 'reply_to');
228 $from = getPref($data_dir, $username, 'full_name');
229 $from_addr = getPref($data_dir, $username, 'email_address');
232 if ($from_addr == '')
233 $from_addr = $popuser.'@'.$domain;
235 $to_list = getLineOfAddrs($to);
236 $cc_list = getLineOfAddrs($cc);
237 $bcc_list = getLineOfAddrs($bcc);
239 /* Encoding 8-bit characters and making from line */
240 $subject = encodeHeader($subject);
242 $from = "<$from_addr>";
244 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
246 /* This creates an RFC 822 date */
247 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
249 /* Create a message-id */
250 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
251 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
253 /* Make an RFC822 Received: line */
254 if (isset($REMOTE_HOST))
255 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
257 $received_from = $REMOTE_ADDR;
259 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
260 if ($HTTP_X_FORWARDED_FOR == '')
261 $HTTP_X_FORWARDED_FOR = 'unknown';
262 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
265 $header = "Received: from $received_from\r\n";
266 $header .= " (SquirrelMail authenticated user $username)\r\n";
267 $header .= " by $SERVER_NAME with HTTP;\r\n";
268 $header .= " $date\r\n";
270 /* Insert the rest of the header fields */
271 $header .= "Message-ID: $message_id\r\n";
272 $header .= "Date: $date\r\n";
273 $header .= "Subject: $subject\r\n";
274 $header .= "From: $from\r\n";
275 $header .= "To: $to_list\r\n"; // Who it's TO
277 /* Insert headers from the $more_headers array */
278 if(is_array($more_headers)) {
279 reset($more_headers);
280 while(list($h_name, $h_val) = each($more_headers)) {
281 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
286 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
290 $header .= "Reply-To: $reply_to\r\n";
294 // BCCs is removed from header by sendmail
295 $header .= "Bcc: $bcc_list\r\n";
299 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
302 $header .= "MIME-Version: 1.0\r\n";
305 $header .= 'Content-Type: multipart/mixed; boundary="';
306 $header .= mimeBoundary();
309 if ($default_charset != '')
310 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
312 $header .= "Content-Type: text/plain;\r\n";
313 $header .= "Content-Transfer-Encoding: 8bit\r\n";
315 $header .= "\r\n"; // One blank line to separate header and body
317 $headerlength = strlen($header);
321 fputs ($fp, $header);
323 return $headerlength;
327 function writeBody ($fp, $passedBody) {
328 global $default_charset;
330 $attachmentlength = 0;
333 $body = '--'.mimeBoundary()."\r\n";
335 if ($default_charset != "")
336 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
338 $body .= "Content-Type: text/plain\r\n";
340 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
341 $body .= $passedBody . "\r\n\r\n";
344 $attachmentlength = attachFiles($fp);
346 if (!isset($postbody)) $postbody = "";
347 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
348 fputs ($fp, $postbody);
350 $body = $passedBody . "\r\n";
353 fputs ($fp, $postbody);
356 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
359 // Send mail using the sendmail command
360 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
361 global $sendmail_path, $popuser, $username, $domain;
363 // Build envelope sender address. Make sure it doesn't contain
364 // spaces or other "weird" chars that would allow a user to
365 // exploit the shell/pipe it is used in.
366 $envelopefrom = "$popuser@$domain";
367 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
368 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
369 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
371 // open pipe to sendmail or qmail-inject (qmail-inject doesn't accept -t param)
372 if (strstr($sendmail_path, "qmail-inject")) {
373 $fp = popen (escapeshellcmd("$sendmail_path -f$envelopefrom"), "w");
375 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
378 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
379 $bodylength = writeBody($fp, $body);
383 return ($headerlength +
$bodylength);
386 function smtpReadData($smtpConnection) {
387 $read = fgets($smtpConnection, 1024);
391 $data[$counter] = $read;
392 $read = fgets($smtpConnection, 1024);
397 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
398 global $username, $popuser, $domain, $version, $smtpServerAddress,
399 $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
402 $to = expandRcptAddrs(parseAddrs($t));
403 $cc = expandRcptAddrs(parseAddrs($c));
404 $bcc = expandRcptAddrs(parseAddrs($b));
405 if (isset($identity) && $identity != 'default')
406 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
408 $from_addr = getPref($data_dir, $username, 'email_address');
411 $from_addr = "$popuser@$domain";
413 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
414 if (!$smtpConnection) {
415 echo 'Error connecting to SMTP Server.<br>';
416 echo "$errorNumber : $errorString<br>";
419 $tmp = fgets($smtpConnection, 1024);
420 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
422 $to_list = getLineOfAddrs($to);
423 $cc_list = getLineOfAddrs($cc);
425 /** Lets introduce ourselves */
426 if (! isset ($use_authenticated_smtp) ||
$use_authenticated_smtp == false) {
427 fputs($smtpConnection, "HELO $domain\r\n");
428 $tmp = fgets($smtpConnection, 1024);
429 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
431 fputs($smtpConnection, "EHLO $domain\r\n");
432 $tmp = fgets($smtpConnection, 1024);
433 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
435 fputs($smtpConnection, "AUTH LOGIN\r\n");
436 $tmp = fgets($smtpConnection, 1024);
437 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
439 fputs($smtpConnection, base64_encode ($username) . "\r\n");
440 $tmp = fgets($smtpConnection, 1024);
441 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
443 fputs($smtpConnection, base64_encode (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
444 $tmp = fgets($smtpConnection, 1024);
445 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
448 /** Ok, who is sending the message? */
449 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
450 $tmp = fgets($smtpConnection, 1024);
451 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
453 /** send who the recipients are */
454 for ($i = 0; $i < count($to); $i++
) {
455 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
456 $tmp = fgets($smtpConnection, 1024);
457 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
459 for ($i = 0; $i < count($cc); $i++
) {
460 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
461 $tmp = fgets($smtpConnection, 1024);
462 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
464 for ($i = 0; $i < count($bcc); $i++
) {
465 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
466 $tmp = fgets($smtpConnection, 1024);
467 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
470 /** Lets start sending the actual message */
471 fputs($smtpConnection, "DATA\r\n");
472 $tmp = fgets($smtpConnection, 1024);
473 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
476 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
477 $bodylength = writeBody($smtpConnection, $body);
479 fputs($smtpConnection, ".\r\n"); // end the DATA part
480 $tmp = fgets($smtpConnection, 1024);
481 $num = errorCheck($tmp, $smtpConnection, true);
483 $tmp = nl2br(htmlspecialchars($tmp));
484 displayPageHeader($color, 'None');
485 include_once('../functions/display_messages.php');
486 $msg = "Message not sent!<br>\nReason given: $tmp";
487 plain_error_message($msg, $color);
491 fputs($smtpConnection, "QUIT\r\n"); // log off
493 fclose($smtpConnection);
495 return ($headerlength +
$bodylength);
499 function errorCheck($line, $smtpConnection, $verbose = false) {
502 // Read new lines on a multiline response
504 while(ereg("^[0-9]+-", $line)) {
505 $line = fgets($smtpConnection, 1024);
512 $err_num = substr($line, 0, strpos($line, " "));
514 case 500: $message = 'Syntax error; command not recognized';
517 case 501: $message = 'Syntax error in parameters or arguments';
520 case 502: $message = 'Command not implemented';
523 case 503: $message = 'Bad sequence of commands';
526 case 504: $message = 'Command parameter not implemented';
531 case 211: $message = 'System status, or system help reply';
534 case 214: $message = 'Help message';
539 case 220: $message = 'Service ready';
542 case 221: $message = 'Service closing transmission channel';
545 case 421: $message = 'Service not available, closing chanel';
549 case 235: return(5); break;
550 case 250: $message = 'Requested mail action okay, completed';
553 case 251: $message = 'User not local; will forward';
556 case 334: return(5); break;
557 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
560 case 550: $message = 'Requested action not taken: mailbox unavailable';
563 case 451: $message = 'Requested action aborted: error in processing';
566 case 551: $message = 'User not local; please try forwarding';
569 case 452: $message = 'Requested action not taken: insufficient system storage';
572 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
575 case 553: $message = 'Requested action not taken: mailbox name not allowed';
578 case 354: $message = 'Start mail input; end with .';
581 case 554: $message = 'Transaction failed';
584 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
591 include_once('../functions/page_header.php');
592 displayPageHeader($color, 'None');
593 include_once('../functions/display_messages.php');
594 $lines = nl2br(htmlspecialchars($lines));
595 $msg = $message . "<br>\nServer replied: $lines";
596 plain_error_message($msg, $color);
598 if (! $verbose) return $status;
602 function sendMessage($t, $c, $b, $subject, $body, $reply_id, $prio = 3) {
603 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad;
604 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
605 global $default_use_priority;
606 global $more_headers;
607 $more_headers = Array();
609 do_hook("smtp_send");
611 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
613 if (isset($reply_id) && $reply_id) {
614 sqimap_mailbox_select ($imap_stream, $mailbox);
615 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
617 // Insert In-Reply-To and References headers if the
618 // message-id of the message we reply to is set (longer than "<>")
619 // The References header should really be the old Referenced header
620 // with the message ID appended, but it can be only the message ID too.
621 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
622 if(strlen($hdr->message_id
) > 2) {
623 $more_headers['In-Reply-To'] = $hdr->message_id
;
624 $more_headers['References'] = $hdr->message_id
;
627 if ($default_use_priority) {
628 $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
631 // In order to remove the problem of users not able to create
632 // messages with "." on a blank line, RFC821 has made provision
633 // in section 4.5.2 (Transparency).
634 $body = ereg_replace("\n\\.", "\n..", $body);
635 $body = ereg_replace("^\\.", "..", $body);
637 // this is to catch all plain \n instances and
638 // replace them with \r\n. All newlines were converted
639 // into just \n inside the compose.php file.
640 $body = ereg_replace("\n", "\r\n", $body);
643 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
645 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
648 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
649 sqimap_append ($imap_stream, $sent_folder, $length);
650 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
651 writeBody ($imap_stream, $body);
652 sqimap_append_done ($imap_stream);
654 sqimap_logout($imap_stream);
655 // Delete the files uploaded for attaching (if any).
656 // only if $length != 0 (if there was no error)
663 function createPriorityHeaders($prio) {
664 $prio_headers = Array();
665 $prio_headers["X-Priority"] = $prio;
668 case 1: $prio_headers["Importance"] = "High";
669 $prio_headers["X-MSMail-Priority"] = "High";
672 case 3: $prio_headers["Importance"] = "Normal";
673 $prio_headers["X-MSMail-Priority"] = "Normal";
677 $prio_headers["Importance"] = "Low";
678 $prio_headers["X-MSMail-Priority"] = "Low";
681 return $prio_headers;