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 $header .= "Content-Type: $filetype; name=\"" .
130 $info['remotefilename'] . "\"\r\n";
131 $header .= "Content-Disposition: attachment; filename=\"" .
132 $info['remotefilename'] . "\"\r\n";
134 /* Use 'rb' for NT systems -- read binary
135 * Unix doesn't care -- everything's binary! :-)
138 $filename = $hashed_attachment_dir . '/' . $info['localfilename'];
139 $file = fopen ($filename, 'rb');
140 if (substr($filetype, 0, 5) == 'text/' ||
141 $filetype == 'message/rfc822') {
143 fputs ($fp, $header);
144 $length +
= strlen($header);
145 while ($tmp = fgets($file, 4096)) {
146 $tmp = str_replace("\r\n", "\n", $tmp);
147 $tmp = str_replace("\r", "\n", $tmp);
148 $tmp = str_replace("\n", "\r\n", $tmp);
149 if (feof($fp) && substr($tmp, -2) != "\r\n") {
153 $length +
= strlen($tmp);
156 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
157 fputs ($fp, $header);
158 $length +
= strlen($header);
159 while ($tmp = fread($file, 570)) {
160 $encoded = chunk_split(base64_encode($tmp));
161 $length +
= strlen($encoded);
162 fputs ($fp, $encoded);
171 /* Delete files that are uploaded for attaching
173 function deleteAttachments() {
174 global $attachments, $attachment_dir;
176 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
179 while (list($localname, $remotename) = each($attachments)) {
180 if (!ereg ("\\/", $localname)) {
181 $filename = $hashed_attachment_dir . '/' . $localname;
183 unlink ("$filename.info");
189 /* Return a nice MIME-boundary
191 function mimeBoundary () {
192 static $mimeBoundaryString;
194 if ($mimeBoundaryString == "") {
195 $mimeBoundaryString = "----=_" .
196 GenerateRandomString(60, '\'()+,-./:=?_', 7);
199 return $mimeBoundaryString;
202 /* Time offset for correct timezone */
203 function timezone () {
206 $diff_second = date('Z');
208 $diff_second = - $diff_second;
210 if ($diff_second > 0) {
217 $diff_second = abs($diff_second);
219 $diff_hour = floor ($diff_second / 3600);
220 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
222 $zonename = '('.strftime('%Z').')';
223 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
227 /* Print all the needed RFC822 headers */
228 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
229 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
230 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
231 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
232 global $REMOTE_HOST, $identity;
234 /* Storing the header to make sure the header is the same
235 * everytime the header is printed.
237 static $header, $headerlength;
240 $to = expandAddrs(parseAddrs($t));
241 $cc = expandAddrs(parseAddrs($c));
242 $bcc = expandAddrs(parseAddrs($b));
243 if (isset($identity) && $identity != 'default') {
244 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
245 $from = getPref($data_dir, $username, 'full_name' . $identity);
246 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
248 $reply_to = getPref($data_dir, $username, 'reply_to');
249 $from = getPref($data_dir, $username, 'full_name');
250 $from_addr = getPref($data_dir, $username, 'email_address');
253 if ($from_addr == '') {
254 $from_addr = $popuser.'@'.$domain;
257 $to_list = getLineOfAddrs($to);
258 $cc_list = getLineOfAddrs($cc);
259 $bcc_list = getLineOfAddrs($bcc);
261 /* Encoding 8-bit characters and making from line */
262 $subject = encodeHeader($subject);
264 $from = "<$from_addr>";
267 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
270 /* This creates an RFC 822 date */
271 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
273 /* Create a message-id */
274 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
275 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
277 /* Make an RFC822 Received: line */
278 if (isset($REMOTE_HOST)) {
279 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
282 $received_from = $REMOTE_ADDR;
285 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
286 if ($HTTP_X_FORWARDED_FOR == '') {
287 $HTTP_X_FORWARDED_FOR = 'unknown';
289 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
292 $header = "Received: from $received_from\r\n";
293 $header .= " (SquirrelMail authenticated user $username)\r\n";
294 $header .= " by $SERVER_NAME with HTTP;\r\n";
295 $header .= " $date\r\n";
297 /* Insert the rest of the header fields */
298 $header .= "Message-ID: $message_id\r\n";
299 $header .= "Date: $date\r\n";
300 $header .= "Subject: $subject\r\n";
301 $header .= "From: $from\r\n";
302 $header .= "To: $to_list\r\n"; // Who it's TO
304 /* Insert headers from the $more_headers array */
305 if(is_array($more_headers)) {
306 reset($more_headers);
307 while(list($h_name, $h_val) = each($more_headers)) {
308 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
313 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
316 if ($reply_to != '') {
317 $header .= "Reply-To: $reply_to\r\n";
322 // BCCs is removed from header by sendmail
323 $header .= "Bcc: $bcc_list\r\n";
327 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; /* Identify SquirrelMail */
329 /* Do the MIME-stuff */
330 $header .= "MIME-Version: 1.0\r\n";
333 $header .= 'Content-Type: multipart/mixed; boundary="';
334 $header .= mimeBoundary();
337 if ($default_charset != '') {
338 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
341 $header .= "Content-Type: text/plain;\r\n";
343 $header .= "Content-Transfer-Encoding: 8bit\r\n";
345 $header .= "\r\n"; // One blank line to separate header and body
347 $headerlength = strlen($header);
350 /* Write the header */
351 fputs ($fp, $header);
353 return $headerlength;
358 function writeBody ($fp, $passedBody) {
359 global $default_charset;
361 $attachmentlength = 0;
364 $body = '--'.mimeBoundary()."\r\n";
366 if ($default_charset != "") {
367 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
370 $body .= "Content-Type: text/plain\r\n";
373 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
374 $body .= $passedBody . "\r\n\r\n";
377 $attachmentlength = attachFiles($fp);
379 if (!isset($postbody)) {
382 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
383 fputs ($fp, $postbody);
385 $body = $passedBody . "\r\n";
388 fputs ($fp, $postbody);
391 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
394 /* Send mail using the sendmail command
396 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
397 global $sendmail_path, $popuser, $username, $domain;
399 /* Build envelope sender address. Make sure it doesn't contain
400 * spaces or other "weird" chars that would allow a user to
401 * exploit the shell/pipe it is used in.
403 $envelopefrom = "$popuser@$domain";
404 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
405 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
406 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
408 /* open pipe to sendmail or qmail-inject (qmail-inject doesn't accept -t param) */
409 if (strstr($sendmail_path, "qmail-inject")) {
410 $fp = popen (escapeshellcmd("$sendmail_path -f$envelopefrom"), "w");
412 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
415 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
416 $bodylength = writeBody($fp, $body);
420 return ($headerlength +
$bodylength);
423 function smtpReadData($smtpConnection) {
424 $read = fgets($smtpConnection, 1024);
428 $data[$counter] = $read;
429 $read = fgets($smtpConnection, 1024);
434 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
435 global $username, $popuser, $domain, $version, $smtpServerAddress,
436 $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
439 $to = expandRcptAddrs(parseAddrs($t));
440 $cc = expandRcptAddrs(parseAddrs($c));
441 $bcc = expandRcptAddrs(parseAddrs($b));
442 if (isset($identity) && $identity != 'default') {
443 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
446 $from_addr = getPref($data_dir, $username, 'email_address');
450 $from_addr = "$popuser@$domain";
453 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
454 if (!$smtpConnection) {
455 echo 'Error connecting to SMTP Server.<br>';
456 echo "$errorNumber : $errorString<br>";
459 $tmp = fgets($smtpConnection, 1024);
460 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
462 $to_list = getLineOfAddrs($to);
463 $cc_list = getLineOfAddrs($cc);
465 /* Lets introduce ourselves */
466 if (! isset ($use_authenticated_smtp) ||
$use_authenticated_smtp == false) {
467 fputs($smtpConnection, "HELO $domain\r\n");
468 $tmp = fgets($smtpConnection, 1024);
469 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
471 fputs($smtpConnection, "EHLO $domain\r\n");
472 $tmp = fgets($smtpConnection, 1024);
473 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
475 fputs($smtpConnection, "AUTH LOGIN\r\n");
476 $tmp = fgets($smtpConnection, 1024);
477 if (errorCheck($tmp, $smtpConnection)!=5) {
481 fputs($smtpConnection, base64_encode ($username) . "\r\n");
482 $tmp = fgets($smtpConnection, 1024);
483 if (errorCheck($tmp, $smtpConnection)!=5) {
487 fputs($smtpConnection, base64_encode (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
488 $tmp = fgets($smtpConnection, 1024);
489 if (errorCheck($tmp, $smtpConnection)!=5) {
494 /* Ok, who is sending the message? */
495 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
496 $tmp = fgets($smtpConnection, 1024);
497 if (errorCheck($tmp, $smtpConnection)!=5) {
501 /* send who the recipients are */
502 for ($i = 0; $i < count($to); $i++
) {
503 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
504 $tmp = fgets($smtpConnection, 1024);
505 if (errorCheck($tmp, $smtpConnection)!=5) {
509 for ($i = 0; $i < count($cc); $i++
) {
510 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
511 $tmp = fgets($smtpConnection, 1024);
512 if (errorCheck($tmp, $smtpConnection)!=5) {
516 for ($i = 0; $i < count($bcc); $i++
) {
517 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
518 $tmp = fgets($smtpConnection, 1024);
519 if (errorCheck($tmp, $smtpConnection)!=5) {
524 /* Lets start sending the actual message */
525 fputs($smtpConnection, "DATA\r\n");
526 $tmp = fgets($smtpConnection, 1024);
527 if (errorCheck($tmp, $smtpConnection)!=5) {
531 /* Send the message */
532 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
533 $bodylength = writeBody($smtpConnection, $body);
535 fputs($smtpConnection, ".\r\n"); /* end the DATA part */
536 $tmp = fgets($smtpConnection, 1024);
537 $num = errorCheck($tmp, $smtpConnection, true);
539 $tmp = nl2br(htmlspecialchars($tmp));
540 displayPageHeader($color, 'None');
541 include_once('../functions/display_messages.php');
542 $msg = "Message not sent!<br>\nReason given: $tmp";
543 plain_error_message($msg, $color);
547 fputs($smtpConnection, "QUIT\r\n"); /* log off */
549 fclose($smtpConnection);
551 return ($headerlength +
$bodylength);
555 function errorCheck($line, $smtpConnection, $verbose = false) {
558 /* Read new lines on a multiline response */
560 while(ereg("^[0-9]+-", $line)) {
561 $line = fgets($smtpConnection, 1024);
568 $err_num = substr($line, 0, strpos($line, " "));
570 case 500: $message = 'Syntax error; command not recognized';
573 case 501: $message = 'Syntax error in parameters or arguments';
576 case 502: $message = 'Command not implemented';
579 case 503: $message = 'Bad sequence of commands';
582 case 504: $message = 'Command parameter not implemented';
586 case 211: $message = 'System status, or system help reply';
589 case 214: $message = 'Help message';
593 case 220: $message = 'Service ready';
596 case 221: $message = 'Service closing transmission channel';
600 case 421: $message = 'Service not available, closing chanel';
606 case 250: $message = 'Requested mail action okay, completed';
609 case 251: $message = 'User not local; will forward';
612 case 334: return(5); break;
613 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
616 case 550: $message = 'Requested action not taken: mailbox unavailable';
619 case 451: $message = 'Requested action aborted: error in processing';
622 case 551: $message = 'User not local; please try forwarding';
625 case 452: $message = 'Requested action not taken: insufficient system storage';
628 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
631 case 553: $message = 'Requested action not taken: mailbox name not allowed';
634 case 354: $message = 'Start mail input; end with .';
637 case 554: $message = 'Transaction failed';
640 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
647 include_once('../functions/page_header.php');
648 displayPageHeader($color, 'None');
649 include_once('../functions/display_messages.php');
650 $lines = nl2br(htmlspecialchars($lines));
651 $msg = $message . "<br>\nServer replied: $lines";
652 plain_error_message($msg, $color);
654 if (! $verbose) return $status;
658 function sendMessage($t, $c, $b, $subject, $body, $reply_id, $prio = 3) {
659 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad;
660 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
661 global $default_use_priority;
662 global $more_headers;
663 $more_headers = Array();
665 do_hook("smtp_send");
667 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
669 if (isset($reply_id) && $reply_id) {
670 sqimap_mailbox_select ($imap_stream, $mailbox);
671 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
673 /* Insert In-Reply-To and References headers if the
674 * message-id of the message we reply to is set (longer than "<>")
675 * The References header should really be the old Referenced header
676 * with the message ID appended, but it can be only the message ID too.
678 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
679 if(strlen($hdr->message_id
) > 2) {
680 $more_headers['In-Reply-To'] = $hdr->message_id
;
681 $more_headers['References'] = $hdr->message_id
;
684 if ($default_use_priority) {
685 $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
688 /* In order to remove the problem of users not able to create
689 * messages with "." on a blank line, RFC821 has made provision
690 * in section 4.5.2 (Transparency).
692 $body = ereg_replace("\n\\.", "\n..", $body);
693 $body = ereg_replace("^\\.", "..", $body);
695 /* this is to catch all plain \n instances and
696 * replace them with \r\n. All newlines were converted
697 * into just \n inside the compose.php file.
699 $body = ereg_replace("\n", "\r\n", $body);
702 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
704 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
707 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
708 sqimap_append ($imap_stream, $sent_folder, $length);
709 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
710 writeBody ($imap_stream, $body);
711 sqimap_append_done ($imap_stream);
713 sqimap_logout($imap_stream);
714 /* Delete the files uploaded for attaching (if any).
715 * only if $length != 0 (if there was no error)
723 function createPriorityHeaders($prio) {
724 $prio_headers = Array();
725 $prio_headers["X-Priority"] = $prio;
728 case 1: $prio_headers["Importance"] = "High";
729 $prio_headers["X-MSMail-Priority"] = "High";
732 case 3: $prio_headers["Importance"] = "Normal";
733 $prio_headers["X-MSMail-Priority"] = "Normal";
737 $prio_headers["Importance"] = "Low";
738 $prio_headers["X-MSMail-Priority"] = "Low";
741 return $prio_headers;