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) {
39 if (count($attachments)>0) {
40 for ($i=0 ; $i < count($attachments) ; $i++) {
41 if ($attachments[$i]->session == $session) {
51 /* looks up aliases in the addressbook and expands them to
54 * Adds @$domain if it wasn't in the address book and if it
55 * doesn't have an @ symbol in it
57 function expandAddrs ($array) {
60 /* don't show errors -- kinda critical that we don't see
61 * them here since the redirect won't work if we do show them
63 $abook = addressbook_init(false, true);
64 for ($i=0; $i < count($array); $i++
) {
65 $result = $abook->lookup($array[$i]);
67 if (isset($result['email'])) {
68 if (isset($result['name'])) {
69 $ret = '"'.$result['name'].'" ';
71 $ret .= '<'.$result['email'].'>';
76 if (strpos($array[$i], '@') === false) {
77 $array[$i] .= '@' . $domain;
79 $array[$i] = '<' . $array[$i] . '>';
86 /* looks up aliases in the addressbook and expands them to
87 * the RFC 821 valid RCPT address. ie <user@example.com>
88 * Adds @$domain if it wasn't in the address book and if it
89 * doesn't have an @ symbol in it
91 function expandRcptAddrs ($array) {
94 /* don't show errors -- kinda critical that we don't see
95 * them here since the redirect won't work if we do show them
97 $abook = addressbook_init(false, true);
98 for ($i=0; $i < count($array); $i++
) {
99 $result = $abook->lookup($array[$i]);
101 if (isset($result['email'])) {
102 $ret = '<'.$result['email'].'>';
106 if (strpos($array[$i], '@') === false) {
107 $array[$i] .= '@' . $domain;
109 $array[$i] = '<' . $array[$i] . '>';
116 /* Attach the files that are due to be attached
118 function attachFiles ($fp, $session) {
119 global $attachments, $attachment_dir, $username;
123 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
124 if (isMultipart($session)) {
125 foreach ($attachments as $info) {
126 if ($info['session'] == $session) {
127 if (isset($info['type'])) {
128 $filetype = $info['type'];
131 $filetype = 'application/octet-stream';
134 $header = '--' . mimeBoundary() . "\r\n";
135 if ( isset($info['remotefilename']) && $info['remotefilename'] != '') {
136 $header .= "Content-Type: $filetype; name=\"" .
137 $info['remotefilename'] . "\"\r\n";
138 $header .= "Content-Disposition: attachment; filename=\"" .
139 $info['remotefilename'] . "\"\r\n";
141 $header .= "Content-Type: $filetype;\r\n";
145 /* Use 'rb' for NT systems -- read binary
146 * Unix doesn't care -- everything's binary! :-)
149 $filename = $hashed_attachment_dir . '/' . $info['localfilename'];
150 $file = fopen ($filename, 'rb');
151 if (substr($filetype, 0, 5) == 'text/' ||
152 substr($filetype, 0, 8) == 'message/' ) {
154 fputs ($fp, $header);
155 $length +
= strlen($header);
156 while ($tmp = fgets($file, 4096)) {
157 $tmp = str_replace("\r\n", "\n", $tmp);
158 $tmp = str_replace("\r", "\n", $tmp);
159 $tmp = str_replace("\n", "\r\n", $tmp);
160 if (feof($fp) && substr($tmp, -2) != "\r\n") {
164 $length +
= strlen($tmp);
167 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
168 fputs ($fp, $header);
169 $length +
= strlen($header);
170 while ($tmp = fread($file, 570)) {
171 $encoded = chunk_split(base64_encode($tmp));
172 $length +
= strlen($encoded);
173 fputs ($fp, $encoded);
183 /* Delete files that are uploaded for attaching
185 function deleteAttachments($session) {
186 global $username, $attachments, $attachment_dir;
187 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
189 $rem_attachments = array();
190 foreach ($attachments as $info) {
191 if ($info['session'] == $session) {
192 $attached_file = "$hashed_attachment_dir/$info[localfilename]";
193 if (file_exists($attached_file)) {
194 unlink($attached_file);
197 $rem_attachments[] = $info;
200 $attachments = $rem_attachments;
206 // $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
207 // if (isMultipart($ses)) {
208 // reset($attachments);
209 // while (list($localname, $remotename, $session) = each($attachments)) {
210 // if ($session == $ses) {
211 /// if (!ereg ("\\/", $localname)) {
212 // $filename = $hashed_attachment_dir . '/' . $localname;
213 // unlink ($filename);
214 // unlink ("$filename.info");
221 /* Return a nice MIME-boundary
223 function mimeBoundary () {
224 static $mimeBoundaryString;
226 if ( !isset( $mimeBoundaryString ) ||
227 $mimeBoundaryString == '') {
228 $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
229 mt_rand( 10000, 99999 );
232 return $mimeBoundaryString;
235 /* Time offset for correct timezone */
236 function timezone () {
239 $diff_second = date('Z');
241 $diff_second = - $diff_second;
243 if ($diff_second > 0) {
250 $diff_second = abs($diff_second);
252 $diff_hour = floor ($diff_second / 3600);
253 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
255 $zonename = '('.strftime('%Z').')';
256 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
260 /* Print all the needed RFC822 headers */
261 function write822Header ($fp, $t, $c, $b, $subject, $more_headers, $session) {
262 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
263 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
264 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
265 global $REMOTE_HOST, $identity;
267 /* Storing the header to make sure the header is the same
268 * everytime the header is printed.
270 static $header, $headerlength;
273 $to = expandAddrs(parseAddrs($t));
274 $cc = expandAddrs(parseAddrs($c));
275 $bcc = expandAddrs(parseAddrs($b));
276 if (isset($identity) && $identity != 'default') {
277 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
278 $from = getPref($data_dir, $username, 'full_name' . $identity);
279 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
281 $reply_to = getPref($data_dir, $username, 'reply_to');
282 $from = getPref($data_dir, $username, 'full_name');
283 $from_addr = getPref($data_dir, $username, 'email_address');
286 if ($from_addr == '') {
287 $from_addr = $popuser.'@'.$domain;
290 $to_list = getLineOfAddrs($to);
291 $cc_list = getLineOfAddrs($cc);
292 $bcc_list = getLineOfAddrs($bcc);
294 /* Encoding 8-bit characters and making from line */
295 $subject = encodeHeader($subject);
297 $from = "<$from_addr>";
300 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
303 /* This creates an RFC 822 date */
304 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
306 /* Create a message-id */
307 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
308 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
310 /* Make an RFC822 Received: line */
311 if (isset($REMOTE_HOST)) {
312 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
315 $received_from = $REMOTE_ADDR;
318 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
319 if ($HTTP_X_FORWARDED_FOR == '') {
320 $HTTP_X_FORWARDED_FOR = 'unknown';
322 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
325 $header = "Received: from $received_from\r\n";
326 $header .= " (SquirrelMail authenticated user $username)\r\n";
327 $header .= " by $SERVER_NAME with HTTP;\r\n";
328 $header .= " $date\r\n";
330 /* Insert the rest of the header fields */
331 $header .= "Message-ID: $message_id\r\n";
332 $header .= "Date: $date\r\n";
333 $header .= "Subject: $subject\r\n";
334 $header .= "From: $from\r\n";
335 $header .= "To: $to_list\r\n"; // Who it's TO
337 if (isset($more_headers["Content-Type"])) {
338 $contentType = $more_headers["Content-Type"];
339 unset($more_headers["Content-Type"]);
342 if (isMultipart($session)) {
343 $contentType = "multipart/mixed;";
346 if ($default_charset != '') {
347 $contentType = 'text/plain; charset='.$default_charset;
350 $contentType = 'text/plain;';
355 /* Insert headers from the $more_headers array */
356 if(is_array($more_headers)) {
357 reset($more_headers);
358 while(list($h_name, $h_val) = each($more_headers)) {
359 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
364 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
367 if ($reply_to != '') {
368 $header .= "Reply-To: $reply_to\r\n";
373 // BCCs is removed from header by sendmail
374 $header .= "Bcc: $bcc_list\r\n";
378 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; /* Identify SquirrelMail */
380 /* Do the MIME-stuff */
381 $header .= "MIME-Version: 1.0\r\n";
383 if (isMultipart($session)) {
384 $header .= 'Content-Type: '.$contentType.' boundary="';
385 $header .= mimeBoundary();
388 $header .= 'Content-Type: '.$contentType."\r\n";
389 $header .= "Content-Transfer-Encoding: 8bit\r\n";
391 $header .= "\r\n"; // One blank line to separate header and body
393 $headerlength = strlen($header);
396 /* Write the header */
397 fputs ($fp, $header);
399 return $headerlength;
404 function writeBody ($fp, $passedBody, $session) {
405 global $default_charset;
407 $attachmentlength = 0;
409 if (isMultipart($session)) {
410 $body = '--'.mimeBoundary()."\r\n";
412 if ($default_charset != "") {
413 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
416 $body .= "Content-Type: text/plain\r\n";
419 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
420 $body .= $passedBody . "\r\n\r\n";
423 $attachmentlength = attachFiles($fp, $session);
425 if (!isset($postbody)) {
428 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
429 fputs ($fp, $postbody);
431 $body = $passedBody . "\r\n";
434 fputs ($fp, $postbody);
437 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
440 /* Send mail using the sendmail command
442 function sendSendmail($t, $c, $b, $subject, $body, $more_headers, $session) {
443 global $sendmail_path, $popuser, $username, $domain;
445 /* Build envelope sender address. Make sure it doesn't contain
446 * spaces or other "weird" chars that would allow a user to
447 * exploit the shell/pipe it is used in.
449 $envelopefrom = "$popuser@$domain";
450 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
451 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
452 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
454 /* open pipe to sendmail or qmail-inject (qmail-inject doesn't accept -t param) */
455 if (strstr($sendmail_path, "qmail-inject")) {
456 $fp = popen (escapeshellcmd("$sendmail_path -f$envelopefrom"), "w");
458 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
461 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers, $session);
462 $bodylength = writeBody($fp, $body, $session);
466 return ($headerlength +
$bodylength);
469 function smtpReadData($smtpConnection) {
470 $read = fgets($smtpConnection, 1024);
474 $data[$counter] = $read;
475 $read = fgets($smtpConnection, 1024);
480 function sendSMTP($t, $c, $b, $subject, $body, $more_headers, $session) {
481 global $username, $popuser, $domain, $version, $smtpServerAddress,
482 $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
485 $to = expandRcptAddrs(parseAddrs($t));
486 $cc = expandRcptAddrs(parseAddrs($c));
487 $bcc = expandRcptAddrs(parseAddrs($b));
488 if (isset($identity) && $identity != 'default') {
489 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
492 $from_addr = getPref($data_dir, $username, 'email_address');
496 $from_addr = "$popuser@$domain";
499 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
500 if (!$smtpConnection) {
501 echo 'Error connecting to SMTP Server.<br>';
502 echo "$errorNumber : $errorString<br>";
505 $tmp = fgets($smtpConnection, 1024);
506 if (errorCheck($tmp, $smtpConnection)!=5) {
510 $to_list = getLineOfAddrs($to);
511 $cc_list = getLineOfAddrs($cc);
513 /* Lets introduce ourselves */
514 if (! isset ($use_authenticated_smtp) ||
$use_authenticated_smtp == false) {
515 fputs($smtpConnection, "HELO $domain\r\n");
516 $tmp = fgets($smtpConnection, 1024);
517 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
519 fputs($smtpConnection, "EHLO $domain\r\n");
520 $tmp = fgets($smtpConnection, 1024);
521 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
523 fputs($smtpConnection, "AUTH LOGIN\r\n");
524 $tmp = fgets($smtpConnection, 1024);
525 if (errorCheck($tmp, $smtpConnection)!=5) {
529 fputs($smtpConnection, base64_encode ($username) . "\r\n");
530 $tmp = fgets($smtpConnection, 1024);
531 if (errorCheck($tmp, $smtpConnection)!=5) {
535 fputs($smtpConnection, base64_encode (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
536 $tmp = fgets($smtpConnection, 1024);
537 if (errorCheck($tmp, $smtpConnection)!=5) {
542 /* Ok, who is sending the message? */
543 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
544 $tmp = fgets($smtpConnection, 1024);
545 if (errorCheck($tmp, $smtpConnection)!=5) {
549 /* send who the recipients are */
550 for ($i = 0; $i < count($to); $i++
) {
551 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
552 $tmp = fgets($smtpConnection, 1024);
553 if (errorCheck($tmp, $smtpConnection)!=5) {
557 for ($i = 0; $i < count($cc); $i++
) {
558 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
559 $tmp = fgets($smtpConnection, 1024);
560 if (errorCheck($tmp, $smtpConnection)!=5) {
564 for ($i = 0; $i < count($bcc); $i++
) {
565 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
566 $tmp = fgets($smtpConnection, 1024);
567 if (errorCheck($tmp, $smtpConnection)!=5) {
572 /* Lets start sending the actual message */
573 fputs($smtpConnection, "DATA\r\n");
574 $tmp = fgets($smtpConnection, 1024);
575 if (errorCheck($tmp, $smtpConnection)!=5) {
579 /* Send the message */
580 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers, $session);
581 $bodylength = writeBody($smtpConnection, $body, $session);
583 fputs($smtpConnection, ".\r\n"); /* end the DATA part */
584 $tmp = fgets($smtpConnection, 1024);
585 $num = errorCheck($tmp, $smtpConnection, true);
590 fputs($smtpConnection, "QUIT\r\n"); /* log off */
592 fclose($smtpConnection);
594 return ($headerlength +
$bodylength);
598 function errorCheck($line, $smtpConnection, $verbose = false) {
599 global $color, $compose_new_win;
601 /* Read new lines on a multiline response */
603 while(ereg("^[0-9]+-", $line)) {
604 $line = fgets($smtpConnection, 1024);
611 $err_num = substr($line, 0, strpos($line, " "));
613 case 500: $message = 'Syntax error; command not recognized';
616 case 501: $message = 'Syntax error in parameters or arguments';
619 case 502: $message = 'Command not implemented';
622 case 503: $message = 'Bad sequence of commands';
625 case 504: $message = 'Command parameter not implemented';
629 case 211: $message = 'System status, or system help reply';
632 case 214: $message = 'Help message';
636 case 220: $message = 'Service ready';
639 case 221: $message = 'Service closing transmission channel';
643 case 421: $message = 'Service not available, closing chanel';
649 case 250: $message = 'Requested mail action okay, completed';
652 case 251: $message = 'User not local; will forward';
655 case 334: return(5); break;
656 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
659 case 550: $message = 'Requested action not taken: mailbox unavailable';
662 case 451: $message = 'Requested action aborted: error in processing';
665 case 551: $message = 'User not local; please try forwarding';
668 case 452: $message = 'Requested action not taken: insufficient system storage';
671 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
674 case 553: $message = 'Requested action not taken: mailbox name not allowed';
677 case 354: $message = 'Start mail input; end with .';
680 case 554: $message = 'Transaction failed';
683 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
690 include_once('../functions/page_header.php');
691 if ($compose_new_win == '1') {
692 compose_Header($color, 'None');
695 displayPageHeader($color, 'None');
697 include_once('../functions/display_messages.php');
698 $lines = nl2br(htmlspecialchars($lines));
699 $msg = $message . "<br>\nServer replied: $lines";
700 plain_error_message($msg, $color);
702 if (! $verbose) return $status;
706 function sendMessage($t, $c, $b, $subject, $body, $reply_id, $MDN, $prio = 3, $session) {
707 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad,
708 $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress,
709 $imapPort, $default_use_priority, $more_headers, $request_mdn, $request_dr;
711 $more_headers = Array();
713 do_hook('smtp_send');
715 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
717 if (isset($reply_id) && $reply_id) {
718 sqimap_mailbox_select ($imap_stream, $mailbox);
719 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
721 /* Insert In-Reply-To and References headers if the
722 * message-id of the message we reply to is set (longer than "<>")
723 * The References header should really be the old Referenced header
724 * with the message ID appended, but it can be only the message ID too.
726 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
727 if(strlen($hdr->message_id
) > 2) {
728 $more_headers['In-Reply-To'] = $hdr->message_id
;
729 $more_headers['References'] = $hdr->message_id
;
732 if ($default_use_priority) {
733 $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
737 if (isset($request_dr)) {
740 if (isset($request_mdn)) {
743 if ( $requestRecipt > 0) {
744 $more_headers = array_merge($more_headers, createReceiptHeaders($requestRecipt));
747 /* In order to remove the problem of users not able to create
748 * messages with "." on a blank line, RFC821 has made provision
749 * in section 4.5.2 (Transparency).
751 $body = ereg_replace("\n\\.", "\n..", $body);
752 $body = ereg_replace("^\\.", "..", $body);
754 /* this is to catch all plain \n instances and
755 * replace them with \r\n. All newlines were converted
756 * into just \n inside the compose.php file.
758 $body = ereg_replace("\n", "\r\n", $body);
761 $more_headers["Content-Type"] = "multipart/report; ".
762 "report-type=disposition-notification;";
766 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers, $session);
768 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers, $session);
770 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
771 sqimap_append ($imap_stream, $sent_folder, $length);
772 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers, $session);
773 writeBody ($imap_stream, $body, $session);
774 sqimap_append_done ($imap_stream);
776 sqimap_logout($imap_stream);
777 /* Delete the files uploaded for attaching (if any).
778 * only if $length != 0 (if there was no error)
781 ClearAttachments($session);
787 function createPriorityHeaders($prio) {
788 $prio_headers = Array();
789 $prio_headers['X-Priority'] = $prio;
792 case 1: $prio_headers['Importance'] = 'High';
793 $prio_headers['X-MSMail-Priority'] = 'High';
796 case 3: $prio_headers['Importance'] = 'Normal';
797 $prio_headers['X-MSMail-Priority'] = 'Normal';
801 $prio_headers['Importance'] = 'Low';
802 $prio_headers['X-MSMail-Priority'] = 'Low';
805 return $prio_headers;
808 function createReceiptHeaders($receipt) {
810 GLOBAL $data_dir, $username;
812 $receipt_headers = Array();
813 $from_addr = getPref($data_dir, $username, 'email_address');
814 $from = getPref($data_dir, $username, 'full_name');
817 $from = "<$from_addr>";
820 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
826 $receipt_headers["Return-Receipt-To"] = $from;
832 $receipt_headers["X-Confirm-Reading-To"] = $from;
834 $receipt_headers["Disposition-Notification-To"] = $from;
836 return $receipt_headers;