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);
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);
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 $filetype == 'message/rfc822' ||
$filetype == 'message/disposition-notification' ) {
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, $MDN, $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;
241 /* Storing the header to make sure the header is the same
242 * everytime the header is printed.
244 static $header, $headerlength;
247 $to = expandAddrs(parseAddrs($t));
248 $cc = expandAddrs(parseAddrs($c));
249 $bcc = expandAddrs(parseAddrs($b));
250 if (isset($identity) && $identity != 'default') {
251 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
252 $from = getPref($data_dir, $username, 'full_name' . $identity);
253 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
255 $reply_to = getPref($data_dir, $username, 'reply_to');
256 $from = getPref($data_dir, $username, 'full_name');
257 $from_addr = getPref($data_dir, $username, 'email_address');
260 if ($from_addr == '') {
261 $from_addr = $popuser.'@'.$domain;
264 $to_list = getLineOfAddrs($to);
265 $cc_list = getLineOfAddrs($cc);
266 $bcc_list = getLineOfAddrs($bcc);
268 /* Encoding 8-bit characters and making from line */
269 $subject = encodeHeader($subject);
271 $from = "<$from_addr>";
274 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
277 /* This creates an RFC 822 date */
278 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
280 /* Create a message-id */
281 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
282 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
284 /* Make an RFC822 Received: line */
285 if (isset($REMOTE_HOST)) {
286 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
289 $received_from = $REMOTE_ADDR;
292 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
293 if ($HTTP_X_FORWARDED_FOR == '') {
294 $HTTP_X_FORWARDED_FOR = 'unknown';
296 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
299 $header = "Received: from $received_from\r\n";
300 $header .= " (SquirrelMail authenticated user $username)\r\n";
301 $header .= " by $SERVER_NAME with HTTP;\r\n";
302 $header .= " $date\r\n";
304 /* Insert the rest of the header fields */
305 $header .= "Message-ID: $message_id\r\n";
306 $header .= "Date: $date\r\n";
307 $header .= "Subject: $subject\r\n";
308 $header .= "From: $from\r\n";
309 $header .= "To: $to_list\r\n"; // Who it's TO
311 if (isset($request_mdn)) {
312 $more_headers["Disposition-Notification-To"] = "$from_addr";
315 /* Insert headers from the $more_headers array */
316 if(is_array($more_headers)) {
317 reset($more_headers);
318 while(list($h_name, $h_val) = each($more_headers)) {
319 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
324 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
327 if ($reply_to != '') {
328 $header .= "Reply-To: $reply_to\r\n";
333 // BCCs is removed from header by sendmail
334 $header .= "Bcc: $bcc_list\r\n";
338 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; /* Identify SquirrelMail */
340 /* Do the MIME-stuff */
341 $header .= "MIME-Version: 1.0\r\n";
345 $header .= "Content-Type: multipart/report;\r\n";
346 $header .= " report-type=disposition-notification;\r\n";
347 $header .= ' boundary="';
348 $header .= mimeBoundary();
352 $header .= 'Content-Type: multipart/mixed; boundary="';
353 $header .= mimeBoundary();
357 if ($default_charset != '') {
358 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
361 $header .= "Content-Type: text/plain;\r\n";
363 $header .= "Content-Transfer-Encoding: 8bit\r\n";
365 $header .= "\r\n"; // One blank line to separate header and body
367 $headerlength = strlen($header);
370 /* Write the header */
371 fputs ($fp, $header);
373 return $headerlength;
378 function writeBody ($fp, $passedBody) {
379 global $default_charset;
381 $attachmentlength = 0;
384 $body = '--'.mimeBoundary()."\r\n";
386 if ($default_charset != "") {
387 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
390 $body .= "Content-Type: text/plain\r\n";
393 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
394 $body .= $passedBody . "\r\n\r\n";
397 $attachmentlength = attachFiles($fp);
399 if (!isset($postbody)) {
402 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
403 fputs ($fp, $postbody);
405 $body = $passedBody . "\r\n";
408 fputs ($fp, $postbody);
411 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
414 /* Send mail using the sendmail command
416 function sendSendmail($t, $c, $b, $subject, $body, $MDN, $more_headers) {
417 global $sendmail_path, $popuser, $username, $domain;
419 /* Build envelope sender address. Make sure it doesn't contain
420 * spaces or other "weird" chars that would allow a user to
421 * exploit the shell/pipe it is used in.
423 $envelopefrom = "$popuser@$domain";
424 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
425 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
426 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
428 /* open pipe to sendmail or qmail-inject (qmail-inject doesn't accept -t param) */
429 if (strstr($sendmail_path, "qmail-inject")) {
430 $fp = popen (escapeshellcmd("$sendmail_path -f$envelopefrom"), "w");
432 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
435 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $MDN, $more_headers);
436 $bodylength = writeBody($fp, $body);
440 return ($headerlength +
$bodylength);
443 function smtpReadData($smtpConnection) {
444 $read = fgets($smtpConnection, 1024);
448 $data[$counter] = $read;
449 $read = fgets($smtpConnection, 1024);
454 function sendSMTP($t, $c, $b, $subject, $body, $MDN, $more_headers) {
455 global $username, $popuser, $domain, $version, $smtpServerAddress,
456 $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
459 $to = expandRcptAddrs(parseAddrs($t));
460 $cc = expandRcptAddrs(parseAddrs($c));
461 $bcc = expandRcptAddrs(parseAddrs($b));
462 if (isset($identity) && $identity != 'default') {
463 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
466 $from_addr = getPref($data_dir, $username, 'email_address');
470 $from_addr = "$popuser@$domain";
473 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
474 if (!$smtpConnection) {
475 echo 'Error connecting to SMTP Server.<br>';
476 echo "$errorNumber : $errorString<br>";
479 $tmp = fgets($smtpConnection, 1024);
480 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
482 $to_list = getLineOfAddrs($to);
483 $cc_list = getLineOfAddrs($cc);
485 /* Lets introduce ourselves */
486 if (! isset ($use_authenticated_smtp) ||
$use_authenticated_smtp == false) {
487 fputs($smtpConnection, "HELO $domain\r\n");
488 $tmp = fgets($smtpConnection, 1024);
489 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
491 fputs($smtpConnection, "EHLO $domain\r\n");
492 $tmp = fgets($smtpConnection, 1024);
493 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
495 fputs($smtpConnection, "AUTH LOGIN\r\n");
496 $tmp = fgets($smtpConnection, 1024);
497 if (errorCheck($tmp, $smtpConnection)!=5) {
501 fputs($smtpConnection, base64_encode ($username) . "\r\n");
502 $tmp = fgets($smtpConnection, 1024);
503 if (errorCheck($tmp, $smtpConnection)!=5) {
507 fputs($smtpConnection, base64_encode (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
508 $tmp = fgets($smtpConnection, 1024);
509 if (errorCheck($tmp, $smtpConnection)!=5) {
514 /* Ok, who is sending the message? */
515 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
516 $tmp = fgets($smtpConnection, 1024);
517 if (errorCheck($tmp, $smtpConnection)!=5) {
521 /* send who the recipients are */
522 for ($i = 0; $i < count($to); $i++
) {
523 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
524 $tmp = fgets($smtpConnection, 1024);
525 if (errorCheck($tmp, $smtpConnection)!=5) {
529 for ($i = 0; $i < count($cc); $i++
) {
530 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
531 $tmp = fgets($smtpConnection, 1024);
532 if (errorCheck($tmp, $smtpConnection)!=5) {
536 for ($i = 0; $i < count($bcc); $i++
) {
537 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
538 $tmp = fgets($smtpConnection, 1024);
539 if (errorCheck($tmp, $smtpConnection)!=5) {
544 /* Lets start sending the actual message */
545 fputs($smtpConnection, "DATA\r\n");
546 $tmp = fgets($smtpConnection, 1024);
547 if (errorCheck($tmp, $smtpConnection)!=5) {
551 /* Send the message */
552 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $MDN, $more_headers);
553 $bodylength = writeBody($smtpConnection, $body);
555 fputs($smtpConnection, ".\r\n"); /* end the DATA part */
556 $tmp = fgets($smtpConnection, 1024);
557 $num = errorCheck($tmp, $smtpConnection, true);
559 $tmp = nl2br(htmlspecialchars($tmp));
560 displayPageHeader($color, 'None');
561 include_once('../functions/display_messages.php');
562 $msg = "Message not sent!<br>\nReason given: $tmp";
563 plain_error_message($msg, $color);
567 fputs($smtpConnection, "QUIT\r\n"); /* log off */
569 fclose($smtpConnection);
571 return ($headerlength +
$bodylength);
575 function errorCheck($line, $smtpConnection, $verbose = false) {
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 displayPageHeader($color, 'None');
669 include_once('../functions/display_messages.php');
670 $lines = nl2br(htmlspecialchars($lines));
671 $msg = $message . "<br>\nServer replied: $lines";
672 plain_error_message($msg, $color);
674 if (! $verbose) return $status;
678 function sendMessage($t, $c, $b, $subject, $body, $reply_id, $MDN, $prio = 3) {
679 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad,
680 $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort,
681 $default_use_priority,
685 $more_headers = Array();
687 do_hook('smtp_send');
689 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
691 if (isset($reply_id) && $reply_id) {
692 sqimap_mailbox_select ($imap_stream, $mailbox);
693 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
695 /* Insert In-Reply-To and References headers if the
696 * message-id of the message we reply to is set (longer than "<>")
697 * The References header should really be the old Referenced header
698 * with the message ID appended, but it can be only the message ID too.
700 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
701 if(strlen($hdr->message_id
) > 2) {
702 $more_headers['In-Reply-To'] = $hdr->message_id
;
703 $more_headers['References'] = $hdr->message_id
;
706 if ($default_use_priority) {
707 $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
710 /* In order to remove the problem of users not able to create
711 * messages with "." on a blank line, RFC821 has made provision
712 * in section 4.5.2 (Transparency).
714 $body = ereg_replace("\n\\.", "\n..", $body);
715 $body = ereg_replace("^\\.", "..", $body);
717 /* this is to catch all plain \n instances and
718 * replace them with \r\n. All newlines were converted
719 * into just \n inside the compose.php file.
721 $body = ereg_replace("\n", "\r\n", $body);
724 $length = sendSendmail($t, $c, $b, $subject, $body, $MDN, $more_headers);
726 $length = sendSMTP($t, $c, $b, $subject, $body, $MDN, $more_headers);
728 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
729 sqimap_append ($imap_stream, $sent_folder, $length);
730 write822Header ($imap_stream, $t, $c, $b, $subject, $MDN, $more_headers);
731 writeBody ($imap_stream, $body);
732 sqimap_append_done ($imap_stream);
734 sqimap_logout($imap_stream);
735 /* Delete the files uploaded for attaching (if any).
736 * only if $length != 0 (if there was no error)
745 function createPriorityHeaders($prio) {
746 $prio_headers = Array();
747 $prio_headers['X-Priority'] = $prio;
750 case 1: $prio_headers['Importance'] = 'High';
751 $prio_headers['X-MSMail-Priority'] = 'High';
754 case 3: $prio_headers['Importance'] = 'Normal';
755 $prio_headers['X-MSMail-Priority'] = 'Normal';
759 $prio_headers['Importance'] = 'Low';
760 $prio_headers['X-MSMail-Priority'] = 'Low';
763 return $prio_headers;