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 () {
38 if (count($attachments)>0) {
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) {
114 global $attachments, $attachment_dir, $username;
118 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
120 foreach ($attachments as $info) {
121 if (isset($info['type'])) {
122 $filetype = $info['type'];
125 $filetype = 'application/octet-stream';
128 $header = '--' . mimeBoundary() . "\r\n";
129 if ( isset($info['remotefilename']) && $info['remotefilename'] != '') {
130 $header .= "Content-Type: $filetype; name=\"" .
131 $info['remotefilename'] . "\"\r\n";
132 $header .= "Content-Disposition: attachment; filename=\"" .
133 $info['remotefilename'] . "\"\r\n";
135 $header .= "Content-Type: $filetype;\r\n";
139 /* Use 'rb' for NT systems -- read binary
140 * Unix doesn't care -- everything's binary! :-)
143 $filename = $hashed_attachment_dir . '/' . $info['localfilename'];
144 $file = fopen ($filename, 'rb');
145 if (substr($filetype, 0, 5) == 'text/' ||
146 substr($filetype, 0, 8) == 'message/' ) {
148 fputs ($fp, $header);
149 $length +
= strlen($header);
150 while ($tmp = fgets($file, 4096)) {
151 $tmp = str_replace("\r\n", "\n", $tmp);
152 $tmp = str_replace("\r", "\n", $tmp);
153 $tmp = str_replace("\n", "\r\n", $tmp);
154 if (feof($fp) && substr($tmp, -2) != "\r\n") {
158 $length +
= strlen($tmp);
161 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
162 fputs ($fp, $header);
163 $length +
= strlen($header);
164 while ($tmp = fread($file, 570)) {
165 $encoded = chunk_split(base64_encode($tmp));
166 $length +
= strlen($encoded);
167 fputs ($fp, $encoded);
176 /* Delete files that are uploaded for attaching
178 function deleteAttachments() {
179 global $attachments, $attachment_dir;
181 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
184 while (list($localname, $remotename) = each($attachments)) {
185 if (!ereg ("\\/", $localname)) {
186 $filename = $hashed_attachment_dir . '/' . $localname;
188 unlink ("$filename.info");
194 /* Return a nice MIME-boundary
196 function mimeBoundary () {
197 static $mimeBoundaryString;
199 if ( !isset( $mimeBoundaryString ) ||
200 $mimeBoundaryString == '') {
201 $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
202 mt_rand( 10000, 99999 );
205 return $mimeBoundaryString;
208 /* Time offset for correct timezone */
209 function timezone () {
212 $diff_second = date('Z');
214 $diff_second = - $diff_second;
216 if ($diff_second > 0) {
223 $diff_second = abs($diff_second);
225 $diff_hour = floor ($diff_second / 3600);
226 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
228 $zonename = '('.strftime('%Z').')';
229 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
233 /* Print all the needed RFC822 headers */
234 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
235 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
236 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
237 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
238 global $REMOTE_HOST, $identity;
240 /* Storing the header to make sure the header is the same
241 * everytime the header is printed.
243 static $header, $headerlength;
246 $to = expandAddrs(parseAddrs($t));
247 $cc = expandAddrs(parseAddrs($c));
248 $bcc = expandAddrs(parseAddrs($b));
249 if (isset($identity) && $identity != 'default') {
250 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
251 $from = getPref($data_dir, $username, 'full_name' . $identity);
252 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
254 $reply_to = getPref($data_dir, $username, 'reply_to');
255 $from = getPref($data_dir, $username, 'full_name');
256 $from_addr = getPref($data_dir, $username, 'email_address');
259 if ($from_addr == '') {
260 $from_addr = $popuser.'@'.$domain;
263 $to_list = getLineOfAddrs($to);
264 $cc_list = getLineOfAddrs($cc);
265 $bcc_list = getLineOfAddrs($bcc);
267 /* Encoding 8-bit characters and making from line */
268 $subject = encodeHeader($subject);
270 $from = "<$from_addr>";
273 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
276 /* This creates an RFC 822 date */
277 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
279 /* Create a message-id */
280 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
281 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
283 /* Make an RFC822 Received: line */
284 if (isset($REMOTE_HOST)) {
285 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
288 $received_from = $REMOTE_ADDR;
291 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
292 if ($HTTP_X_FORWARDED_FOR == '') {
293 $HTTP_X_FORWARDED_FOR = 'unknown';
295 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
298 $header = "Received: from $received_from\r\n";
299 $header .= " (SquirrelMail authenticated user $username)\r\n";
300 $header .= " by $SERVER_NAME with HTTP;\r\n";
301 $header .= " $date\r\n";
303 /* Insert the rest of the header fields */
304 $header .= "Message-ID: $message_id\r\n";
305 $header .= "Date: $date\r\n";
306 $header .= "Subject: $subject\r\n";
307 $header .= "From: $from\r\n";
308 $header .= "To: $to_list\r\n"; // Who it's TO
310 if (isset($more_headers["Content-Type"])) {
311 $contentType = $more_headers["Content-Type"];
312 unset($more_headers["Content-Type"]);
316 $contentType = "multipart/mixed;";
319 if ($default_charset != '') {
320 $contentType = 'text/plain; charset='.$default_charset;
323 $contentType = 'text/plain;';
328 /* Insert headers from the $more_headers array */
329 if(is_array($more_headers)) {
330 reset($more_headers);
331 while(list($h_name, $h_val) = each($more_headers)) {
332 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
337 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
340 if ($reply_to != '') {
341 $header .= "Reply-To: $reply_to\r\n";
346 // BCCs is removed from header by sendmail
347 $header .= "Bcc: $bcc_list\r\n";
351 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; /* Identify SquirrelMail */
353 /* Do the MIME-stuff */
354 $header .= "MIME-Version: 1.0\r\n";
357 $header .= 'Content-Type: '.$contentType.' boundary="';
358 $header .= mimeBoundary();
361 $header .= 'Content-Type: '.$contentType."\r\n";
362 $header .= "Content-Transfer-Encoding: 8bit\r\n";
364 $header .= "\r\n"; // One blank line to separate header and body
366 $headerlength = strlen($header);
369 /* Write the header */
370 fputs ($fp, $header);
372 return $headerlength;
377 function writeBody ($fp, $passedBody) {
378 global $default_charset;
380 $attachmentlength = 0;
383 $body = '--'.mimeBoundary()."\r\n";
385 if ($default_charset != "") {
386 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
389 $body .= "Content-Type: text/plain\r\n";
392 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
393 $body .= $passedBody . "\r\n\r\n";
396 $attachmentlength = attachFiles($fp);
398 if (!isset($postbody)) {
401 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
402 fputs ($fp, $postbody);
404 $body = $passedBody . "\r\n";
407 fputs ($fp, $postbody);
410 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
413 /* Send mail using the sendmail command
415 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
416 global $sendmail_path, $popuser, $username, $domain;
418 /* Build envelope sender address. Make sure it doesn't contain
419 * spaces or other "weird" chars that would allow a user to
420 * exploit the shell/pipe it is used in.
422 $envelopefrom = "$popuser@$domain";
423 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
424 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
425 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
427 /* open pipe to sendmail or qmail-inject (qmail-inject doesn't accept -t param) */
428 if (strstr($sendmail_path, "qmail-inject")) {
429 $fp = popen (escapeshellcmd("$sendmail_path -f$envelopefrom"), "w");
431 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
434 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
435 $bodylength = writeBody($fp, $body);
439 return ($headerlength +
$bodylength);
442 function smtpReadData($smtpConnection) {
443 $read = fgets($smtpConnection, 1024);
447 $data[$counter] = $read;
448 $read = fgets($smtpConnection, 1024);
453 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
454 global $username, $popuser, $domain, $version, $smtpServerAddress,
455 $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
458 $to = expandRcptAddrs(parseAddrs($t));
459 $cc = expandRcptAddrs(parseAddrs($c));
460 $bcc = expandRcptAddrs(parseAddrs($b));
461 if (isset($identity) && $identity != 'default') {
462 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
465 $from_addr = getPref($data_dir, $username, 'email_address');
469 $from_addr = "$popuser@$domain";
472 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
473 if (!$smtpConnection) {
474 echo 'Error connecting to SMTP Server.<br>';
475 echo "$errorNumber : $errorString<br>";
478 $tmp = fgets($smtpConnection, 1024);
479 if (errorCheck($tmp, $smtpConnection)!=5) {
483 $to_list = getLineOfAddrs($to);
484 $cc_list = getLineOfAddrs($cc);
486 /* Lets introduce ourselves */
487 if (! isset ($use_authenticated_smtp) ||
$use_authenticated_smtp == false) {
488 fputs($smtpConnection, "HELO $domain\r\n");
489 $tmp = fgets($smtpConnection, 1024);
490 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
492 fputs($smtpConnection, "EHLO $domain\r\n");
493 $tmp = fgets($smtpConnection, 1024);
494 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
496 fputs($smtpConnection, "AUTH LOGIN\r\n");
497 $tmp = fgets($smtpConnection, 1024);
498 if (errorCheck($tmp, $smtpConnection)!=5) {
502 fputs($smtpConnection, base64_encode ($username) . "\r\n");
503 $tmp = fgets($smtpConnection, 1024);
504 if (errorCheck($tmp, $smtpConnection)!=5) {
508 fputs($smtpConnection, base64_encode (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
509 $tmp = fgets($smtpConnection, 1024);
510 if (errorCheck($tmp, $smtpConnection)!=5) {
515 /* Ok, who is sending the message? */
516 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
517 $tmp = fgets($smtpConnection, 1024);
518 if (errorCheck($tmp, $smtpConnection)!=5) {
522 /* send who the recipients are */
523 for ($i = 0; $i < count($to); $i++
) {
524 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
525 $tmp = fgets($smtpConnection, 1024);
526 if (errorCheck($tmp, $smtpConnection)!=5) {
530 for ($i = 0; $i < count($cc); $i++
) {
531 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
532 $tmp = fgets($smtpConnection, 1024);
533 if (errorCheck($tmp, $smtpConnection)!=5) {
537 for ($i = 0; $i < count($bcc); $i++
) {
538 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
539 $tmp = fgets($smtpConnection, 1024);
540 if (errorCheck($tmp, $smtpConnection)!=5) {
545 /* Lets start sending the actual message */
546 fputs($smtpConnection, "DATA\r\n");
547 $tmp = fgets($smtpConnection, 1024);
548 if (errorCheck($tmp, $smtpConnection)!=5) {
552 /* Send the message */
553 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
554 $bodylength = writeBody($smtpConnection, $body);
556 fputs($smtpConnection, ".\r\n"); /* end the DATA part */
557 $tmp = fgets($smtpConnection, 1024);
558 $num = errorCheck($tmp, $smtpConnection, true);
563 fputs($smtpConnection, "QUIT\r\n"); /* log off */
565 fclose($smtpConnection);
567 return ($headerlength +
$bodylength);
571 function errorCheck($line, $smtpConnection, $verbose = false) {
572 global $color, $compose_new_win;
574 /* Read new lines on a multiline response */
576 while(ereg("^[0-9]+-", $line)) {
577 $line = fgets($smtpConnection, 1024);
584 $err_num = substr($line, 0, strpos($line, " "));
586 case 500: $message = 'Syntax error; command not recognized';
589 case 501: $message = 'Syntax error in parameters or arguments';
592 case 502: $message = 'Command not implemented';
595 case 503: $message = 'Bad sequence of commands';
598 case 504: $message = 'Command parameter not implemented';
602 case 211: $message = 'System status, or system help reply';
605 case 214: $message = 'Help message';
609 case 220: $message = 'Service ready';
612 case 221: $message = 'Service closing transmission channel';
616 case 421: $message = 'Service not available, closing chanel';
622 case 250: $message = 'Requested mail action okay, completed';
625 case 251: $message = 'User not local; will forward';
628 case 334: return(5); break;
629 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
632 case 550: $message = 'Requested action not taken: mailbox unavailable';
635 case 451: $message = 'Requested action aborted: error in processing';
638 case 551: $message = 'User not local; please try forwarding';
641 case 452: $message = 'Requested action not taken: insufficient system storage';
644 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
647 case 553: $message = 'Requested action not taken: mailbox name not allowed';
650 case 354: $message = 'Start mail input; end with .';
653 case 554: $message = 'Transaction failed';
656 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
663 include_once('../functions/page_header.php');
664 if ($compose_new_win == '1') {
665 compose_Header($color, 'None');
668 displayPageHeader($color, 'None');
670 include_once('../functions/display_messages.php');
671 $lines = nl2br(htmlspecialchars($lines));
672 $msg = $message . "<br>\nServer replied: $lines";
673 plain_error_message($msg, $color);
675 if (! $verbose) return $status;
679 function sendMessage($t, $c, $b, $subject, $body, $reply_id, $MDN, $prio = 3) {
680 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad,
681 $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress,
682 $imapPort, $default_use_priority, $more_headers, $request_mdn, $request_dr;
684 $more_headers = Array();
686 do_hook('smtp_send');
688 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
690 if (isset($reply_id) && $reply_id) {
691 sqimap_mailbox_select ($imap_stream, $mailbox);
692 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
694 /* Insert In-Reply-To and References headers if the
695 * message-id of the message we reply to is set (longer than "<>")
696 * The References header should really be the old Referenced header
697 * with the message ID appended, but it can be only the message ID too.
699 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
700 if(strlen($hdr->message_id
) > 2) {
701 $more_headers['In-Reply-To'] = $hdr->message_id
;
702 $more_headers['References'] = $hdr->message_id
;
705 if ($default_use_priority) {
706 $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
710 if (isset($request_dr)) {
713 if (isset($request_mdn)) {
716 if ( $requestRecipt > 0) {
717 $more_headers = array_merge($more_headers, createReceiptHeaders($requestRecipt));
720 /* In order to remove the problem of users not able to create
721 * messages with "." on a blank line, RFC821 has made provision
722 * in section 4.5.2 (Transparency).
724 $body = ereg_replace("\n\\.", "\n..", $body);
725 $body = ereg_replace("^\\.", "..", $body);
727 /* this is to catch all plain \n instances and
728 * replace them with \r\n. All newlines were converted
729 * into just \n inside the compose.php file.
731 $body = ereg_replace("\n", "\r\n", $body);
734 $more_headers["Content-Type"] = "multipart/report; ".
735 "report-type=disposition-notification;";
739 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
741 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
743 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
744 sqimap_append ($imap_stream, $sent_folder, $length);
745 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
746 writeBody ($imap_stream, $body);
747 sqimap_append_done ($imap_stream);
749 sqimap_logout($imap_stream);
750 /* Delete the files uploaded for attaching (if any).
751 * only if $length != 0 (if there was no error)
760 function createPriorityHeaders($prio) {
761 $prio_headers = Array();
762 $prio_headers['X-Priority'] = $prio;
765 case 1: $prio_headers['Importance'] = 'High';
766 $prio_headers['X-MSMail-Priority'] = 'High';
769 case 3: $prio_headers['Importance'] = 'Normal';
770 $prio_headers['X-MSMail-Priority'] = 'Normal';
774 $prio_headers['Importance'] = 'Low';
775 $prio_headers['X-MSMail-Priority'] = 'Low';
778 return $prio_headers;
781 function createReceiptHeaders($receipt) {
783 GLOBAL $data_dir, $username;
785 $receipt_headers = Array();
786 $from_addr = getPref($data_dir, $username, 'email_address');
787 $from = getPref($data_dir, $username, 'full_name');
790 $from = "<$from_addr>";
793 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
799 $receipt_headers["Return-Receipt-To"] = $from;
805 $receipt_headers["X-Confirm-Reading-To"] = $from;
807 $receipt_headers["Disposition-Notification-To"] = $from;
809 return $receipt_headers;