6 * Copyright (c) 1999-2001 The SquirrelMail Development 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 /*****************************************************************/
16 /*** THIS FILE NEEDS TO HAVE ITS FORMATTING FIXED!!! ***/
17 /*** PLEASE DO SO AND REMOVE THIS COMMENT SECTION. ***/
18 /*** + Base level indent should begin at left margin, as ***/
19 /*** the require_once and global lines below. ***/
20 /*** + All identation should consist of four space blocks ***/
21 /*** + Tab characters are evil. ***/
22 /*** + all comments should use "slash-star ... star-slash" ***/
23 /*** style -- no pound characters, no slash-slash style ***/
24 /*** + FLOW CONTROL STATEMENTS (if, while, etc) SHOULD ***/
25 /*** ALWAYS USE { AND } CHARACTERS!!! ***/
26 /*** + Please use ' instead of ", when possible. Note " ***/
27 /*** should always be used in _( ) function calls. ***/
28 /*** Thank you for your help making the SM code more readable. ***/
29 /*****************************************************************/
31 require_once('../functions/addressbook.php');
32 require_once('../functions/plugin.php');
34 global $username, $popuser, $domain;
36 // This should most probably go to some initialization...
37 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
38 $popuser = $usernamedata[1];
39 $domain = $usernamedata[2];
44 // We need domain for smtp
46 $domain = getenv('HOSTNAME');
48 // Returns true only if this message is multipart
49 function isMultipart () {
52 if (count($attachments)>0)
58 // looks up aliases in the addressbook and expands them to
60 // Adds @$domain if it wasn't in the address book and if it
61 // doesn't have an @ symbol in it
62 function expandAddrs ($array) {
65 // don't show errors -- kinda critical that we don't see
66 // them here since the redirect won't work if we do show them
67 $abook = addressbook_init(false);
68 for ($i=0; $i < count($array); $i++
) {
69 $result = $abook->lookup($array[$i]);
71 if (isset($result['email'])) {
72 if (isset($result['name'])) {
73 $ret = '"'.$result['name'].'" ';
75 $ret .= '<'.$result['email'].'>';
80 if (strpos($array[$i], '@') === false)
81 $array[$i] .= '@' . $domain;
82 $array[$i] = '<' . $array[$i] . '>';
89 // looks up aliases in the addressbook and expands them to
90 // the RFC 821 valid RCPT address. ie <user@example.com>
91 // Adds @$domain if it wasn't in the address book and if it
92 // doesn't have an @ symbol in it
93 function expandRcptAddrs ($array) {
96 // don't show errors -- kinda critical that we don't see
97 // them here since the redirect won't work if we do show them
98 $abook = addressbook_init(false);
99 for ($i=0; $i < count($array); $i++
) {
100 $result = $abook->lookup($array[$i]);
102 if (isset($result['email'])) {
103 $ret = '<'.$result['email'].'>';
108 if (strpos($array[$i], '@') === false)
109 $array[$i] .= '@' . $domain;
110 $array[$i] = '<' . $array[$i] . '>';
117 // Attach the files that are due to be attached
118 function attachFiles ($fp) {
119 global $attachments, $attachment_dir;
124 foreach ($attachments as $info)
126 if (isset($info['type']))
127 $filetype = $info['type'];
129 $filetype = 'application/octet-stream';
131 $header = '--'.mimeBoundary()."\r\n";
132 $header .= "Content-Type: $filetype; name=\"" .
133 $info['remotefilename'] . "\"\r\n";
134 $header .= "Content-Disposition: attachment; filename=\"" .
135 $info['remotefilename'] . "\"\r\n";
137 // Use 'rb' for NT systems -- read binary
138 // Unix doesn't care -- everything's binary! :-)
139 $file = fopen ($attachment_dir . $info['localfilename'], '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")
152 $length +
= strlen($tmp);
155 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
156 fputs ($fp, $header);
157 $length +
= strlen($header);
158 while ($tmp = fread($file, 570)) {
159 $encoded = chunk_split(base64_encode($tmp));
160 $length +
= strlen($encoded);
161 fputs ($fp, $encoded);
171 // Delete files that are uploaded for attaching
172 function deleteAttachments() {
173 global $attachments, $attachment_dir;
177 while (list($localname, $remotename) = each($attachments)) {
178 if (!ereg ("\\/", $localname)) {
179 unlink ($attachment_dir.$localname);
180 unlink ($attachment_dir.$localname.'.info');
186 // Return a nice MIME-boundary
187 function mimeBoundary () {
188 static $mimeBoundaryString;
190 if ($mimeBoundaryString == "") {
191 $mimeBoundaryString = "----=_" .
192 GenerateRandomString(60, '\'()+,-./:=?_', 7);
195 return $mimeBoundaryString;
198 /* Time offset for correct timezone */
199 function timezone () {
202 $diff_second = date('Z');
204 $diff_second = - $diff_second;
205 if ($diff_second > 0)
210 $diff_second = abs($diff_second);
212 $diff_hour = floor ($diff_second / 3600);
213 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
215 $zonename = '('.strftime('%Z').')';
216 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
220 /* Print all the needed RFC822 headers */
221 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
222 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
223 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
224 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
225 global $REMOTE_HOST, $identity;
227 // Storing the header to make sure the header is the same
228 // everytime the header is printed.
229 static $header, $headerlength;
232 $to = expandAddrs(parseAddrs($t));
233 $cc = expandAddrs(parseAddrs($c));
234 $bcc = expandAddrs(parseAddrs($b));
235 if (isset($identity) && $identity != 'default')
237 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
238 $from = getPref($data_dir, $username, 'full_name' . $identity);
239 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
243 $reply_to = getPref($data_dir, $username, 'reply_to');
244 $from = getPref($data_dir, $username, 'full_name');
245 $from_addr = getPref($data_dir, $username, 'email_address');
248 if ($from_addr == '')
249 $from_addr = $popuser.'@'.$domain;
251 $to_list = getLineOfAddrs($to);
252 $cc_list = getLineOfAddrs($cc);
253 $bcc_list = getLineOfAddrs($bcc);
255 /* Encoding 8-bit characters and making from line */
256 $subject = encodeHeader($subject);
258 $from = "<$from_addr>";
260 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
262 /* This creates an RFC 822 date */
263 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
265 /* Create a message-id */
266 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
267 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
269 /* Make an RFC822 Received: line */
270 if (isset($REMOTE_HOST))
271 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
273 $received_from = $REMOTE_ADDR;
275 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
276 if ($HTTP_X_FORWARDED_FOR == '')
277 $HTTP_X_FORWARDED_FOR = 'unknown';
278 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
281 $header = "Received: from $received_from\r\n";
282 $header .= " (SquirrelMail authenticated user $username)\r\n";
283 $header .= " by $SERVER_NAME with HTTP;\r\n";
284 $header .= " $date\r\n";
286 /* Insert the rest of the header fields */
287 $header .= "Message-ID: $message_id\r\n";
288 $header .= "Date: $date\r\n";
289 $header .= "Subject: $subject\r\n";
290 $header .= "From: $from\r\n";
291 $header .= "To: $to_list\r\n"; // Who it's TO
293 /* Insert headers from the $more_headers array */
294 if(is_array($more_headers)) {
295 reset($more_headers);
296 while(list($h_name, $h_val) = each($more_headers)) {
297 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
302 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
306 $header .= "Reply-To: $reply_to\r\n";
310 // BCCs is removed from header by sendmail
311 $header .= "Bcc: $bcc_list\r\n";
315 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
318 $header .= "MIME-Version: 1.0\r\n";
321 $header .= 'Content-Type: multipart/mixed; boundary="';
322 $header .= mimeBoundary();
325 if ($default_charset != '')
326 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
328 $header .= "Content-Type: text/plain;\r\n";
329 $header .= "Content-Transfer-Encoding: 8bit\r\n";
331 $header .= "\r\n"; // One blank line to separate header and body
333 $headerlength = strlen($header);
337 fputs ($fp, $header);
339 return $headerlength;
343 function writeBody ($fp, $passedBody) {
344 global $default_charset;
346 $attachmentlength = 0;
349 $body = '--'.mimeBoundary()."\r\n";
351 if ($default_charset != "")
352 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
354 $body .= "Content-Type: text/plain\r\n";
356 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
357 $body .= $passedBody . "\r\n\r\n";
360 $attachmentlength = attachFiles($fp);
362 if (!isset($postbody)) $postbody = "";
363 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
364 fputs ($fp, $postbody);
366 $body = $passedBody . "\r\n";
369 fputs ($fp, $postbody);
372 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
375 // Send mail using the sendmail command
376 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
377 global $sendmail_path, $popuser, $username, $domain;
379 // Build envelope sender address. Make sure it doesn't contain
380 // spaces or other "weird" chars that would allow a user to
381 // exploit the shell/pipe it is used in.
382 $envelopefrom = "$popuser@$domain";
383 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
384 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
385 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
387 // open pipe to sendmail or qmail-inject (qmail-inject doesn't accept -t param)
388 if (strstr($sendmail_path, "qmail-inject")) {
389 $fp = popen (escapeshellcmd("$sendmail_path -f$envelopefrom"), "w");
391 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
394 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
395 $bodylength = writeBody($fp, $body);
399 return ($headerlength +
$bodylength);
402 function smtpReadData($smtpConnection) {
403 $read = fgets($smtpConnection, 1024);
407 $data[$counter] = $read;
408 $read = fgets($smtpConnection, 1024);
413 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
414 global $username, $popuser, $domain, $version, $smtpServerAddress,
415 $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
418 $to = expandRcptAddrs(parseAddrs($t));
419 $cc = expandRcptAddrs(parseAddrs($c));
420 $bcc = expandRcptAddrs(parseAddrs($b));
421 if (isset($identity) && $identity != 'default')
422 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
424 $from_addr = getPref($data_dir, $username, 'email_address');
427 $from_addr = "$popuser@$domain";
429 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
430 if (!$smtpConnection) {
431 echo 'Error connecting to SMTP Server.<br>';
432 echo "$errorNumber : $errorString<br>";
435 $tmp = fgets($smtpConnection, 1024);
436 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
438 $to_list = getLineOfAddrs($to);
439 $cc_list = getLineOfAddrs($cc);
441 /** Lets introduce ourselves */
442 if (! isset ($use_authenticated_smtp) ||
$use_authenticated_smtp == false) {
443 fputs($smtpConnection, "HELO $domain\r\n");
444 $tmp = fgets($smtpConnection, 1024);
445 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
447 fputs($smtpConnection, "EHLO $domain\r\n");
448 $tmp = fgets($smtpConnection, 1024);
449 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
451 fputs($smtpConnection, "AUTH LOGIN\r\n");
452 $tmp = fgets($smtpConnection, 1024);
453 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
455 fputs($smtpConnection, base64_encode ($username) . "\r\n");
456 $tmp = fgets($smtpConnection, 1024);
457 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
459 fputs($smtpConnection, base64_encode (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
460 $tmp = fgets($smtpConnection, 1024);
461 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
464 /** Ok, who is sending the message? */
465 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
466 $tmp = fgets($smtpConnection, 1024);
467 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
469 /** send who the recipients are */
470 for ($i = 0; $i < count($to); $i++
) {
471 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
472 $tmp = fgets($smtpConnection, 1024);
473 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
475 for ($i = 0; $i < count($cc); $i++
) {
476 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
477 $tmp = fgets($smtpConnection, 1024);
478 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
480 for ($i = 0; $i < count($bcc); $i++
) {
481 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
482 $tmp = fgets($smtpConnection, 1024);
483 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
486 /** Lets start sending the actual message */
487 fputs($smtpConnection, "DATA\r\n");
488 $tmp = fgets($smtpConnection, 1024);
489 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
492 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
493 $bodylength = writeBody($smtpConnection, $body);
495 fputs($smtpConnection, ".\r\n"); // end the DATA part
496 $tmp = fgets($smtpConnection, 1024);
497 $num = errorCheck($tmp, $smtpConnection, true);
499 $tmp = nl2br(htmlspecialchars($tmp));
500 displayPageHeader($color, 'None');
501 include_once('../functions/display_messages.php');
502 $msg = "Message not sent!<br>\nReason given: $tmp";
503 plain_error_message($msg, $color);
507 fputs($smtpConnection, "QUIT\r\n"); // log off
509 fclose($smtpConnection);
511 return ($headerlength +
$bodylength);
515 function errorCheck($line, $smtpConnection, $verbose = false) {
518 // Read new lines on a multiline response
520 while(ereg("^[0-9]+-", $line)) {
521 $line = fgets($smtpConnection, 1024);
528 $err_num = substr($line, 0, strpos($line, " "));
530 case 500: $message = 'Syntax error; command not recognized';
533 case 501: $message = 'Syntax error in parameters or arguments';
536 case 502: $message = 'Command not implemented';
539 case 503: $message = 'Bad sequence of commands';
542 case 504: $message = 'Command parameter not implemented';
547 case 211: $message = 'System status, or system help reply';
550 case 214: $message = 'Help message';
555 case 220: $message = 'Service ready';
558 case 221: $message = 'Service closing transmission channel';
561 case 421: $message = 'Service not available, closing chanel';
565 case 235: return(5); break;
566 case 250: $message = 'Requested mail action okay, completed';
569 case 251: $message = 'User not local; will forward';
572 case 334: return(5); break;
573 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
576 case 550: $message = 'Requested action not taken: mailbox unavailable';
579 case 451: $message = 'Requested action aborted: error in processing';
582 case 551: $message = 'User not local; please try forwarding';
585 case 452: $message = 'Requested action not taken: insufficient system storage';
588 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
591 case 553: $message = 'Requested action not taken: mailbox name not allowed';
594 case 354: $message = 'Start mail input; end with .';
597 case 554: $message = 'Transaction failed';
600 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
607 include_once('../functions/page_header.php');
608 displayPageHeader($color, 'None');
609 include_once('../functions/display_messages.php');
610 $lines = nl2br(htmlspecialchars($lines));
611 $msg = $message . "<br>\nServer replied: $lines";
612 plain_error_message($msg, $color);
614 if (! $verbose) return $status;
618 function sendMessage($t, $c, $b, $subject, $body, $reply_id, $prio = 3) {
619 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad;
620 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
621 global $default_use_priority;
622 global $more_headers;
623 $more_headers = Array();
625 do_hook("smtp_send");
627 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
629 if (isset($reply_id) && $reply_id) {
630 sqimap_mailbox_select ($imap_stream, $mailbox);
631 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
633 // Insert In-Reply-To and References headers if the
634 // message-id of the message we reply to is set (longer than "<>")
635 // The References header should really be the old Referenced header
636 // with the message ID appended, but it can be only the message ID too.
637 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
638 if(strlen($hdr->message_id
) > 2) {
639 $more_headers['In-Reply-To'] = $hdr->message_id
;
640 $more_headers['References'] = $hdr->message_id
;
643 if ($default_use_priority) {
644 $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
647 // In order to remove the problem of users not able to create
648 // messages with "." on a blank line, RFC821 has made provision
649 // in section 4.5.2 (Transparency).
650 $body = ereg_replace("\n\\.", "\n..", $body);
651 $body = ereg_replace("^\\.", "..", $body);
653 // this is to catch all plain \n instances and
654 // replace them with \r\n. All newlines were converted
655 // into just \n inside the compose.php file.
656 $body = ereg_replace("\n", "\r\n", $body);
659 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
661 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
664 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
665 sqimap_append ($imap_stream, $sent_folder, $length);
666 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
667 writeBody ($imap_stream, $body);
668 sqimap_append_done ($imap_stream);
670 sqimap_logout($imap_stream);
671 // Delete the files uploaded for attaching (if any).
672 // only if $length != 0 (if there was no error)
679 function createPriorityHeaders($prio) {
680 $prio_headers = Array();
681 $prio_headers["X-Priority"] = $prio;
684 case 1: $prio_headers["Importance"] = "High";
685 $prio_headers["X-MSMail-Priority"] = "High";
688 case 3: $prio_headers["Importance"] = "Normal";
689 $prio_headers["X-MSMail-Priority"] = "Normal";
693 $prio_headers["Importance"] = "Low";
694 $prio_headers["X-MSMail-Priority"] = "Low";
697 return $prio_headers;