6 * Copyright (c) 1999-2002 The SquirrelMail Project 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');
17 require_once('../functions/prefs.php');
19 global $username, $popuser, $domain;
21 /* This should most probably go to some initialization... */
22 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
23 $popuser = $usernamedata[1];
24 $domain = $usernamedata[2];
29 /* We need domain for smtp */
31 $domain = getenv('HOSTNAME');
34 /* Returns true only if this message is multipart */
35 function isMultipart ($session) {
38 foreach ($attachments as $info) {
39 if ($info['session'] == $session) {
46 /* looks up aliases in the addressbook and expands them to
49 * Adds @$domain if it wasn't in the address book and if it
50 * doesn't have an @ symbol in it
52 function expandAddrs ($array) {
55 /* don't show errors -- kinda critical that we don't see
56 * them here since the redirect won't work if we do show them
58 $abook = addressbook_init(false, true);
59 for ($i=0; $i < count($array); $i++
) {
60 $result = $abook->lookup($array[$i]);
62 if (isset($result['email'])) {
63 if (isset($result['name'])) {
64 $ret = '"'.$result['name'].'" ';
66 $ret .= '<'.$result['email'].'>';
71 if (strpos($array[$i], '@') === false) {
72 $array[$i] .= '@' . $domain;
74 $array[$i] = '<' . $array[$i] . '>';
81 /* looks up aliases in the addressbook and expands them to
82 * the RFC 821 valid RCPT address. ie <user@example.com>
83 * Adds @$domain if it wasn't in the address book and if it
84 * doesn't have an @ symbol in it
86 function expandRcptAddrs ($array) {
89 /* don't show errors -- kinda critical that we don't see
90 * them here since the redirect won't work if we do show them
92 $abook = addressbook_init(false, true);
93 for ($i=0; $i < count($array); $i++
) {
94 $result = $abook->lookup($array[$i]);
96 if (isset($result['email'])) {
97 $ret = '<'.$result['email'].'>';
101 if (strpos($array[$i], '@') === false) {
102 $array[$i] .= '@' . $domain;
104 $array[$i] = '<' . $array[$i] . '>';
111 /* Attach the files that are due to be attached
113 function attachFiles ($fp, $session) {
114 global $attachments, $attachment_dir, $username;
118 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
119 if (isMultipart($session)) {
120 foreach ($attachments as $info) {
121 if ($info['session'] == $session) {
122 if (isset($info['type'])) {
123 $filetype = $info['type'];
126 $filetype = 'application/octet-stream';
129 $header = '--' . mimeBoundary() . "\r\n";
130 if ( isset($info['remotefilename']) && $info['remotefilename'] != '') {
131 $header .= "Content-Type: $filetype; name=\"" .
132 $info['remotefilename'] . "\"\r\n";
133 $header .= "Content-Disposition: attachment; filename=\"" .
134 $info['remotefilename'] . "\"\r\n";
136 $header .= "Content-Type: $filetype;\r\n";
140 /* Use 'rb' for NT systems -- read binary
141 * Unix doesn't care -- everything's binary! :-)
144 $filename = $hashed_attachment_dir . '/' . $info['localfilename'];
145 $file = fopen ($filename, 'rb');
146 if (substr($filetype, 0, 5) == 'text/' ||
147 substr($filetype, 0, 8) == 'message/' ) {
149 fputs ($fp, $header);
150 $length +
= strlen($header);
151 while ($tmp = fgets($file, 4096)) {
152 $tmp = str_replace("\r\n", "\n", $tmp);
153 $tmp = str_replace("\r", "\n", $tmp);
154 $tmp = str_replace("\n", "\r\n", $tmp);
155 if (feof($fp) && substr($tmp, -2) != "\r\n") {
159 $length +
= strlen($tmp);
162 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
163 fputs ($fp, $header);
164 $length +
= strlen($header);
165 while ($tmp = fread($file, 570)) {
166 $encoded = chunk_split(base64_encode($tmp));
167 $length +
= strlen($encoded);
168 fputs ($fp, $encoded);
178 /* Delete files that are uploaded for attaching
180 function deleteAttachments($session) {
181 global $username, $attachments, $attachment_dir;
182 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
184 $rem_attachments = array();
185 foreach ($attachments as $info) {
186 if ($info['session'] == $session) {
187 $attached_file = "$hashed_attachment_dir/$info[localfilename]";
188 if (file_exists($attached_file)) {
189 unlink($attached_file);
192 $rem_attachments[] = $info;
195 $attachments = $rem_attachments;
198 /* Return a nice MIME-boundary
200 function mimeBoundary () {
201 static $mimeBoundaryString;
203 if ( !isset( $mimeBoundaryString ) ||
204 $mimeBoundaryString == '') {
205 $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
206 mt_rand( 10000, 99999 );
209 return $mimeBoundaryString;
212 /* Time offset for correct timezone */
213 function timezone () {
216 $diff_second = date('Z');
218 $diff_second = - $diff_second;
220 if ($diff_second > 0) {
227 $diff_second = abs($diff_second);
229 $diff_hour = floor ($diff_second / 3600);
230 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
232 $zonename = '('.strftime('%Z').')';
233 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
237 /* Print all the needed RFC822 headers */
238 function write822Header ($fp, $t, $c, $b, $subject, $more_headers, $session) {
239 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
240 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
241 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
242 global $REMOTE_HOST, $identity;
244 /* Storing the header to make sure the header is the same
245 * everytime the header is printed.
247 static $header, $headerlength;
250 $to = expandAddrs(parseAddrs($t));
251 $cc = expandAddrs(parseAddrs($c));
252 $bcc = expandAddrs(parseAddrs($b));
253 if (isset($identity) && $identity != 'default') {
254 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
255 $from = getPref($data_dir, $username, 'full_name' . $identity);
256 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
258 $reply_to = getPref($data_dir, $username, 'reply_to');
259 $from = getPref($data_dir, $username, 'full_name');
260 $from_addr = getPref($data_dir, $username, 'email_address');
263 if ($from_addr == '') {
264 $from_addr = $popuser.'@'.$domain;
267 $to_list = getLineOfAddrs($to);
268 $cc_list = getLineOfAddrs($cc);
269 $bcc_list = getLineOfAddrs($bcc);
271 /* Encoding 8-bit characters and making from line */
272 $subject = encodeHeader($subject);
274 $from = "<$from_addr>";
277 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
280 /* This creates an RFC 822 date */
281 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
283 /* Create a message-id */
284 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
285 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
287 /* Make an RFC822 Received: line */
288 if (isset($REMOTE_HOST)) {
289 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
292 $received_from = $REMOTE_ADDR;
295 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
296 if ($HTTP_X_FORWARDED_FOR == '') {
297 $HTTP_X_FORWARDED_FOR = 'unknown';
299 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
302 $header = "Received: from $received_from\r\n";
303 $header .= " (SquirrelMail authenticated user $username)\r\n";
304 $header .= " by $SERVER_NAME with HTTP;\r\n";
305 $header .= " $date\r\n";
307 /* Insert the rest of the header fields */
308 $header .= "Message-ID: $message_id\r\n";
309 $header .= "Date: $date\r\n";
310 $header .= "Subject: $subject\r\n";
311 $header .= "From: $from\r\n";
312 $header .= "To: $to_list\r\n"; // Who it's TO
314 if (isset($more_headers["Content-Type"])) {
315 $contentType = $more_headers["Content-Type"];
316 unset($more_headers["Content-Type"]);
319 if (isMultipart($session)) {
320 $contentType = "multipart/mixed;";
323 if ($default_charset != '') {
324 $contentType = 'text/plain; charset='.$default_charset;
327 $contentType = 'text/plain;';
332 /* Insert headers from the $more_headers array */
333 if(is_array($more_headers)) {
334 reset($more_headers);
335 while(list($h_name, $h_val) = each($more_headers)) {
336 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
341 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
344 if ($reply_to != '') {
345 $header .= "Reply-To: $reply_to\r\n";
350 // BCCs is removed from header by sendmail
351 $header .= "Bcc: $bcc_list\r\n";
355 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; /* Identify SquirrelMail */
357 /* Do the MIME-stuff */
358 $header .= "MIME-Version: 1.0\r\n";
360 if (isMultipart($session)) {
361 $header .= 'Content-Type: '.$contentType.' boundary="';
362 $header .= mimeBoundary();
365 $header .= 'Content-Type: '.$contentType."\r\n";
366 $header .= "Content-Transfer-Encoding: 8bit\r\n";
368 $header .= "\r\n"; // One blank line to separate header and body
370 $headerlength = strlen($header);
373 /* Write the header */
374 fputs ($fp, $header);
376 return $headerlength;
381 function writeBody ($fp, $passedBody, $session) {
382 global $default_charset;
384 $attachmentlength = 0;
386 if (isMultipart($session)) {
387 $body = '--'.mimeBoundary()."\r\n";
389 if ($default_charset != "") {
390 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
393 $body .= "Content-Type: text/plain\r\n";
396 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
397 $body .= $passedBody . "\r\n\r\n";
400 $attachmentlength = attachFiles($fp, $session);
402 if (!isset($postbody)) {
405 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
406 fputs ($fp, $postbody);
408 $body = $passedBody . "\r\n";
411 fputs ($fp, $postbody);
414 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
417 /* Send mail using the sendmail command
419 function sendSendmail($t, $c, $b, $subject, $body, $more_headers, $session) {
420 global $sendmail_path, $popuser, $username, $domain;
422 /* Build envelope sender address. Make sure it doesn't contain
423 * spaces or other "weird" chars that would allow a user to
424 * exploit the shell/pipe it is used in.
426 $envelopefrom = "$popuser@$domain";
427 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
428 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
429 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
431 /* open pipe to sendmail or qmail-inject (qmail-inject doesn't accept -t param) */
432 if (strstr($sendmail_path, "qmail-inject")) {
433 $fp = popen (escapeshellcmd("$sendmail_path -f$envelopefrom"), "w");
435 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
438 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers, $session);
439 $bodylength = writeBody($fp, $body, $session);
443 return ($headerlength +
$bodylength);
446 function smtpReadData($smtpConnection) {
447 $read = fgets($smtpConnection, 1024);
451 $data[$counter] = $read;
452 $read = fgets($smtpConnection, 1024);
457 function sendSMTP($t, $c, $b, $subject, $body, $more_headers, $session) {
458 global $username, $popuser, $domain, $version, $smtpServerAddress,
459 $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
462 $to = expandRcptAddrs(parseAddrs($t));
463 $cc = expandRcptAddrs(parseAddrs($c));
464 $bcc = expandRcptAddrs(parseAddrs($b));
465 if (isset($identity) && $identity != 'default') {
466 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
469 $from_addr = getPref($data_dir, $username, 'email_address');
473 $from_addr = "$popuser@$domain";
476 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
477 if (!$smtpConnection) {
478 echo 'Error connecting to SMTP Server.<br>';
479 echo "$errorNumber : $errorString<br>";
482 $tmp = fgets($smtpConnection, 1024);
483 if (errorCheck($tmp, $smtpConnection)!=5) {
487 $to_list = getLineOfAddrs($to);
488 $cc_list = getLineOfAddrs($cc);
490 /* Lets introduce ourselves */
491 if (! isset ($use_authenticated_smtp) ||
$use_authenticated_smtp == false) {
492 fputs($smtpConnection, "HELO $domain\r\n");
493 $tmp = fgets($smtpConnection, 1024);
494 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
496 fputs($smtpConnection, "EHLO $domain\r\n");
497 $tmp = fgets($smtpConnection, 1024);
498 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
500 fputs($smtpConnection, "AUTH LOGIN\r\n");
501 $tmp = fgets($smtpConnection, 1024);
502 if (errorCheck($tmp, $smtpConnection)!=5) {
506 fputs($smtpConnection, base64_encode ($username) . "\r\n");
507 $tmp = fgets($smtpConnection, 1024);
508 if (errorCheck($tmp, $smtpConnection)!=5) {
512 fputs($smtpConnection, base64_encode (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
513 $tmp = fgets($smtpConnection, 1024);
514 if (errorCheck($tmp, $smtpConnection)!=5) {
519 /* Ok, who is sending the message? */
520 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
521 $tmp = fgets($smtpConnection, 1024);
522 if (errorCheck($tmp, $smtpConnection)!=5) {
526 /* send who the recipients are */
527 for ($i = 0; $i < count($to); $i++
) {
528 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
529 $tmp = fgets($smtpConnection, 1024);
530 if (errorCheck($tmp, $smtpConnection)!=5) {
534 for ($i = 0; $i < count($cc); $i++
) {
535 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
536 $tmp = fgets($smtpConnection, 1024);
537 if (errorCheck($tmp, $smtpConnection)!=5) {
541 for ($i = 0; $i < count($bcc); $i++
) {
542 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
543 $tmp = fgets($smtpConnection, 1024);
544 if (errorCheck($tmp, $smtpConnection)!=5) {
549 /* Lets start sending the actual message */
550 fputs($smtpConnection, "DATA\r\n");
551 $tmp = fgets($smtpConnection, 1024);
552 if (errorCheck($tmp, $smtpConnection)!=5) {
556 /* Send the message */
557 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers, $session);
558 $bodylength = writeBody($smtpConnection, $body, $session);
560 fputs($smtpConnection, ".\r\n"); /* end the DATA part */
561 $tmp = fgets($smtpConnection, 1024);
562 $num = errorCheck($tmp, $smtpConnection, true);
567 fputs($smtpConnection, "QUIT\r\n"); /* log off */
569 fclose($smtpConnection);
571 return ($headerlength +
$bodylength);
575 function errorCheck($line, $smtpConnection, $verbose = false) {
576 global $color, $compose_new_win;
578 /* Read new lines on a multiline response */
580 while(ereg("^[0-9]+-", $line)) {
581 $line = fgets($smtpConnection, 1024);
588 $err_num = substr($line, 0, strpos($line, " "));
590 case 500: $message = 'Syntax error; command not recognized';
593 case 501: $message = 'Syntax error in parameters or arguments';
596 case 502: $message = 'Command not implemented';
599 case 503: $message = 'Bad sequence of commands';
602 case 504: $message = 'Command parameter not implemented';
606 case 211: $message = 'System status, or system help reply';
609 case 214: $message = 'Help message';
613 case 220: $message = 'Service ready';
616 case 221: $message = 'Service closing transmission channel';
620 case 421: $message = 'Service not available, closing chanel';
626 case 250: $message = 'Requested mail action okay, completed';
629 case 251: $message = 'User not local; will forward';
632 case 334: return(5); break;
633 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
636 case 550: $message = 'Requested action not taken: mailbox unavailable';
639 case 451: $message = 'Requested action aborted: error in processing';
642 case 551: $message = 'User not local; please try forwarding';
645 case 452: $message = 'Requested action not taken: insufficient system storage';
648 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
651 case 553: $message = 'Requested action not taken: mailbox name not allowed';
654 case 354: $message = 'Start mail input; end with .';
657 case 554: $message = 'Transaction failed';
660 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
667 include_once('../functions/page_header.php');
668 if ($compose_new_win == '1') {
669 compose_Header($color, 'None');
672 displayPageHeader($color, 'None');
674 include_once('../functions/display_messages.php');
675 $lines = nl2br(htmlspecialchars($lines));
676 $msg = $message . "<br>\nServer replied: $lines";
677 plain_error_message($msg, $color);
679 if (! $verbose) return $status;
683 function sendMessage($t, $c, $b, $subject, $body, $reply_id, $MDN, $prio = 3, $session) {
684 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad,
685 $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress,
686 $imapPort, $default_use_priority, $more_headers, $request_mdn, $request_dr;
688 $more_headers = Array();
690 do_hook('smtp_send');
692 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
694 if (isset($reply_id) && $reply_id) {
695 sqimap_mailbox_select ($imap_stream, $mailbox);
696 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
698 /* Insert In-Reply-To and References headers if the
699 * message-id of the message we reply to is set (longer than "<>")
700 * The References header should really be the old Referenced header
701 * with the message ID appended, but it can be only the message ID too.
703 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
704 if(strlen($hdr->message_id
) > 2) {
705 $more_headers['In-Reply-To'] = $hdr->message_id
;
706 $more_headers['References'] = $hdr->message_id
;
709 if ($default_use_priority) {
710 $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
714 if (isset($request_dr)) {
717 if (isset($request_mdn)) {
720 if ( $requestRecipt > 0) {
721 $more_headers = array_merge($more_headers, createReceiptHeaders($requestRecipt));
724 /* In order to remove the problem of users not able to create
725 * messages with "." on a blank line, RFC821 has made provision
726 * in section 4.5.2 (Transparency).
728 $body = ereg_replace("\n\\.", "\n..", $body);
729 $body = ereg_replace("^\\.", "..", $body);
731 /* this is to catch all plain \n instances and
732 * replace them with \r\n. All newlines were converted
733 * into just \n inside the compose.php file.
735 $body = ereg_replace("\n", "\r\n", $body);
738 $more_headers["Content-Type"] = "multipart/report; ".
739 "report-type=disposition-notification;";
743 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers, $session);
745 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers, $session);
747 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
748 sqimap_append ($imap_stream, $sent_folder, $length);
749 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers, $session);
750 writeBody ($imap_stream, $body, $session);
751 sqimap_append_done ($imap_stream);
753 sqimap_logout($imap_stream);
754 /* Delete the files uploaded for attaching (if any).
755 * only if $length != 0 (if there was no error)
758 ClearAttachments($session);
764 function createPriorityHeaders($prio) {
765 $prio_headers = Array();
766 $prio_headers['X-Priority'] = $prio;
769 case 1: $prio_headers['Importance'] = 'High';
770 $prio_headers['X-MSMail-Priority'] = 'High';
773 case 3: $prio_headers['Importance'] = 'Normal';
774 $prio_headers['X-MSMail-Priority'] = 'Normal';
778 $prio_headers['Importance'] = 'Low';
779 $prio_headers['X-MSMail-Priority'] = 'Low';
782 return $prio_headers;
785 function createReceiptHeaders($receipt) {
787 GLOBAL $data_dir, $username;
789 $receipt_headers = Array();
790 $from_addr = getPref($data_dir, $username, 'email_address');
791 $from = getPref($data_dir, $username, 'full_name');
794 $from = "<$from_addr>";
797 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
803 $receipt_headers["Return-Receipt-To"] = $from;
809 $receipt_headers["X-Confirm-Reading-To"] = $from;
811 $receipt_headers["Disposition-Notification-To"] = $from;
813 return $receipt_headers;