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');
33 require_once('../functions/prefs.php');
35 global $username, $popuser, $domain;
37 // This should most probably go to some initialization...
38 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
39 $popuser = $usernamedata[1];
40 $domain = $usernamedata[2];
45 // We need domain for smtp
47 $domain = getenv('HOSTNAME');
49 // Returns true only if this message is multipart
50 function isMultipart () {
53 if (count($attachments)>0)
59 // looks up aliases in the addressbook and expands them to
61 // Adds @$domain if it wasn't in the address book and if it
62 // doesn't have an @ symbol in it
63 function expandAddrs ($array) {
66 // don't show errors -- kinda critical that we don't see
67 // them here since the redirect won't work if we do show them
68 $abook = addressbook_init(false);
69 for ($i=0; $i < count($array); $i++
) {
70 $result = $abook->lookup($array[$i]);
72 if (isset($result['email'])) {
73 if (isset($result['name'])) {
74 $ret = '"'.$result['name'].'" ';
76 $ret .= '<'.$result['email'].'>';
81 if (strpos($array[$i], '@') === false)
82 $array[$i] .= '@' . $domain;
83 $array[$i] = '<' . $array[$i] . '>';
90 // looks up aliases in the addressbook and expands them to
91 // the RFC 821 valid RCPT address. ie <user@example.com>
92 // Adds @$domain if it wasn't in the address book and if it
93 // doesn't have an @ symbol in it
94 function expandRcptAddrs ($array) {
97 // don't show errors -- kinda critical that we don't see
98 // them here since the redirect won't work if we do show them
99 $abook = addressbook_init(false);
100 for ($i=0; $i < count($array); $i++
) {
101 $result = $abook->lookup($array[$i]);
103 if (isset($result['email'])) {
104 $ret = '<'.$result['email'].'>';
109 if (strpos($array[$i], '@') === false)
110 $array[$i] .= '@' . $domain;
111 $array[$i] = '<' . $array[$i] . '>';
118 // Attach the files that are due to be attached
119 function attachFiles ($fp) {
120 global $attachments, $attachment_dir, $username;
124 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
126 foreach ($attachments as $info)
128 if (isset($info['type']))
129 $filetype = $info['type'];
131 $filetype = 'application/octet-stream';
133 $header = '--'.mimeBoundary()."\r\n";
134 $header .= "Content-Type: $filetype; name=\"" .
135 $info['remotefilename'] . "\"\r\n";
136 $header .= "Content-Disposition: attachment; filename=\"" .
137 $info['remotefilename'] . "\"\r\n";
139 // Use 'rb' for NT systems -- read binary
140 // Unix doesn't care -- everything's binary! :-)
142 $filename = $hashed_attachment_dir . '/' . $info['localfilename'];
143 $file = fopen ($filename, 'rb');
144 if (substr($filetype, 0, 5) == 'text/' ||
145 $filetype == 'message/rfc822') {
147 fputs ($fp, $header);
148 $length +
= strlen($header);
149 while ($tmp = fgets($file, 4096)) {
150 $tmp = str_replace("\r\n", "\n", $tmp);
151 $tmp = str_replace("\r", "\n", $tmp);
152 $tmp = str_replace("\n", "\r\n", $tmp);
153 if (feof($fp) && substr($tmp, -2) != "\r\n")
156 $length +
= strlen($tmp);
159 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
160 fputs ($fp, $header);
161 $length +
= strlen($header);
162 while ($tmp = fread($file, 570)) {
163 $encoded = chunk_split(base64_encode($tmp));
164 $length +
= strlen($encoded);
165 fputs ($fp, $encoded);
175 // Delete files that are uploaded for attaching
176 function deleteAttachments() {
177 global $attachments, $attachment_dir;
179 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
182 while (list($localname, $remotename) = each($attachments)) {
183 if (!ereg ("\\/", $localname)) {
184 $filename = $hashed_attachment_dir . '/' . $localname;
186 unlink ("$filename.info");
192 // Return a nice MIME-boundary
193 function mimeBoundary () {
194 static $mimeBoundaryString;
196 if ($mimeBoundaryString == "") {
197 $mimeBoundaryString = "----=_" .
198 GenerateRandomString(60, '\'()+,-./:=?_', 7);
201 return $mimeBoundaryString;
204 /* Time offset for correct timezone */
205 function timezone () {
208 $diff_second = date('Z');
210 $diff_second = - $diff_second;
211 if ($diff_second > 0)
216 $diff_second = abs($diff_second);
218 $diff_hour = floor ($diff_second / 3600);
219 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
221 $zonename = '('.strftime('%Z').')';
222 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
226 /* Print all the needed RFC822 headers */
227 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
228 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
229 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
230 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
231 global $REMOTE_HOST, $identity;
233 // Storing the header to make sure the header is the same
234 // everytime the header is printed.
235 static $header, $headerlength;
238 $to = expandAddrs(parseAddrs($t));
239 $cc = expandAddrs(parseAddrs($c));
240 $bcc = expandAddrs(parseAddrs($b));
241 if (isset($identity) && $identity != 'default')
243 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
244 $from = getPref($data_dir, $username, 'full_name' . $identity);
245 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
249 $reply_to = getPref($data_dir, $username, 'reply_to');
250 $from = getPref($data_dir, $username, 'full_name');
251 $from_addr = getPref($data_dir, $username, 'email_address');
254 if ($from_addr == '')
255 $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>";
266 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
268 /* This creates an RFC 822 date */
269 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
271 /* Create a message-id */
272 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
273 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
275 /* Make an RFC822 Received: line */
276 if (isset($REMOTE_HOST))
277 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
279 $received_from = $REMOTE_ADDR;
281 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
282 if ($HTTP_X_FORWARDED_FOR == '')
283 $HTTP_X_FORWARDED_FOR = 'unknown';
284 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
287 $header = "Received: from $received_from\r\n";
288 $header .= " (SquirrelMail authenticated user $username)\r\n";
289 $header .= " by $SERVER_NAME with HTTP;\r\n";
290 $header .= " $date\r\n";
292 /* Insert the rest of the header fields */
293 $header .= "Message-ID: $message_id\r\n";
294 $header .= "Date: $date\r\n";
295 $header .= "Subject: $subject\r\n";
296 $header .= "From: $from\r\n";
297 $header .= "To: $to_list\r\n"; // Who it's TO
299 /* Insert headers from the $more_headers array */
300 if(is_array($more_headers)) {
301 reset($more_headers);
302 while(list($h_name, $h_val) = each($more_headers)) {
303 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
308 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
312 $header .= "Reply-To: $reply_to\r\n";
316 // BCCs is removed from header by sendmail
317 $header .= "Bcc: $bcc_list\r\n";
321 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
324 $header .= "MIME-Version: 1.0\r\n";
327 $header .= 'Content-Type: multipart/mixed; boundary="';
328 $header .= mimeBoundary();
331 if ($default_charset != '')
332 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
334 $header .= "Content-Type: text/plain;\r\n";
335 $header .= "Content-Transfer-Encoding: 8bit\r\n";
337 $header .= "\r\n"; // One blank line to separate header and body
339 $headerlength = strlen($header);
343 fputs ($fp, $header);
345 return $headerlength;
349 function writeBody ($fp, $passedBody) {
350 global $default_charset;
352 $attachmentlength = 0;
355 $body = '--'.mimeBoundary()."\r\n";
357 if ($default_charset != "")
358 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
360 $body .= "Content-Type: text/plain\r\n";
362 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
363 $body .= $passedBody . "\r\n\r\n";
366 $attachmentlength = attachFiles($fp);
368 if (!isset($postbody)) $postbody = "";
369 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
370 fputs ($fp, $postbody);
372 $body = $passedBody . "\r\n";
375 fputs ($fp, $postbody);
378 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
381 // Send mail using the sendmail command
382 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
383 global $sendmail_path, $popuser, $username, $domain;
385 // Build envelope sender address. Make sure it doesn't contain
386 // spaces or other "weird" chars that would allow a user to
387 // exploit the shell/pipe it is used in.
388 $envelopefrom = "$popuser@$domain";
389 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
390 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
391 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
393 // open pipe to sendmail or qmail-inject (qmail-inject doesn't accept -t param)
394 if (strstr($sendmail_path, "qmail-inject")) {
395 $fp = popen (escapeshellcmd("$sendmail_path -f$envelopefrom"), "w");
397 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
400 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
401 $bodylength = writeBody($fp, $body);
405 return ($headerlength +
$bodylength);
408 function smtpReadData($smtpConnection) {
409 $read = fgets($smtpConnection, 1024);
413 $data[$counter] = $read;
414 $read = fgets($smtpConnection, 1024);
419 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
420 global $username, $popuser, $domain, $version, $smtpServerAddress,
421 $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
424 $to = expandRcptAddrs(parseAddrs($t));
425 $cc = expandRcptAddrs(parseAddrs($c));
426 $bcc = expandRcptAddrs(parseAddrs($b));
427 if (isset($identity) && $identity != 'default')
428 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
430 $from_addr = getPref($data_dir, $username, 'email_address');
433 $from_addr = "$popuser@$domain";
435 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
436 if (!$smtpConnection) {
437 echo 'Error connecting to SMTP Server.<br>';
438 echo "$errorNumber : $errorString<br>";
441 $tmp = fgets($smtpConnection, 1024);
442 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
444 $to_list = getLineOfAddrs($to);
445 $cc_list = getLineOfAddrs($cc);
447 /** Lets introduce ourselves */
448 if (! isset ($use_authenticated_smtp) ||
$use_authenticated_smtp == false) {
449 fputs($smtpConnection, "HELO $domain\r\n");
450 $tmp = fgets($smtpConnection, 1024);
451 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
453 fputs($smtpConnection, "EHLO $domain\r\n");
454 $tmp = fgets($smtpConnection, 1024);
455 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
457 fputs($smtpConnection, "AUTH LOGIN\r\n");
458 $tmp = fgets($smtpConnection, 1024);
459 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
461 fputs($smtpConnection, base64_encode ($username) . "\r\n");
462 $tmp = fgets($smtpConnection, 1024);
463 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
465 fputs($smtpConnection, base64_encode (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
466 $tmp = fgets($smtpConnection, 1024);
467 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
470 /** Ok, who is sending the message? */
471 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
472 $tmp = fgets($smtpConnection, 1024);
473 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
475 /** send who the recipients are */
476 for ($i = 0; $i < count($to); $i++
) {
477 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
478 $tmp = fgets($smtpConnection, 1024);
479 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
481 for ($i = 0; $i < count($cc); $i++
) {
482 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
483 $tmp = fgets($smtpConnection, 1024);
484 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
486 for ($i = 0; $i < count($bcc); $i++
) {
487 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
488 $tmp = fgets($smtpConnection, 1024);
489 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
492 /** Lets start sending the actual message */
493 fputs($smtpConnection, "DATA\r\n");
494 $tmp = fgets($smtpConnection, 1024);
495 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
498 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
499 $bodylength = writeBody($smtpConnection, $body);
501 fputs($smtpConnection, ".\r\n"); // end the DATA part
502 $tmp = fgets($smtpConnection, 1024);
503 $num = errorCheck($tmp, $smtpConnection, true);
505 $tmp = nl2br(htmlspecialchars($tmp));
506 displayPageHeader($color, 'None');
507 include_once('../functions/display_messages.php');
508 $msg = "Message not sent!<br>\nReason given: $tmp";
509 plain_error_message($msg, $color);
513 fputs($smtpConnection, "QUIT\r\n"); // log off
515 fclose($smtpConnection);
517 return ($headerlength +
$bodylength);
521 function errorCheck($line, $smtpConnection, $verbose = false) {
524 // Read new lines on a multiline response
526 while(ereg("^[0-9]+-", $line)) {
527 $line = fgets($smtpConnection, 1024);
534 $err_num = substr($line, 0, strpos($line, " "));
536 case 500: $message = 'Syntax error; command not recognized';
539 case 501: $message = 'Syntax error in parameters or arguments';
542 case 502: $message = 'Command not implemented';
545 case 503: $message = 'Bad sequence of commands';
548 case 504: $message = 'Command parameter not implemented';
553 case 211: $message = 'System status, or system help reply';
556 case 214: $message = 'Help message';
561 case 220: $message = 'Service ready';
564 case 221: $message = 'Service closing transmission channel';
567 case 421: $message = 'Service not available, closing chanel';
571 case 235: return(5); break;
572 case 250: $message = 'Requested mail action okay, completed';
575 case 251: $message = 'User not local; will forward';
578 case 334: return(5); break;
579 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
582 case 550: $message = 'Requested action not taken: mailbox unavailable';
585 case 451: $message = 'Requested action aborted: error in processing';
588 case 551: $message = 'User not local; please try forwarding';
591 case 452: $message = 'Requested action not taken: insufficient system storage';
594 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
597 case 553: $message = 'Requested action not taken: mailbox name not allowed';
600 case 354: $message = 'Start mail input; end with .';
603 case 554: $message = 'Transaction failed';
606 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
613 include_once('../functions/page_header.php');
614 displayPageHeader($color, 'None');
615 include_once('../functions/display_messages.php');
616 $lines = nl2br(htmlspecialchars($lines));
617 $msg = $message . "<br>\nServer replied: $lines";
618 plain_error_message($msg, $color);
620 if (! $verbose) return $status;
624 function sendMessage($t, $c, $b, $subject, $body, $reply_id, $prio = 3) {
625 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad;
626 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
627 global $default_use_priority;
628 global $more_headers;
629 $more_headers = Array();
631 do_hook("smtp_send");
633 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
635 if (isset($reply_id) && $reply_id) {
636 sqimap_mailbox_select ($imap_stream, $mailbox);
637 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
639 // Insert In-Reply-To and References headers if the
640 // message-id of the message we reply to is set (longer than "<>")
641 // The References header should really be the old Referenced header
642 // with the message ID appended, but it can be only the message ID too.
643 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
644 if(strlen($hdr->message_id
) > 2) {
645 $more_headers['In-Reply-To'] = $hdr->message_id
;
646 $more_headers['References'] = $hdr->message_id
;
649 if ($default_use_priority) {
650 $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
653 // In order to remove the problem of users not able to create
654 // messages with "." on a blank line, RFC821 has made provision
655 // in section 4.5.2 (Transparency).
656 $body = ereg_replace("\n\\.", "\n..", $body);
657 $body = ereg_replace("^\\.", "..", $body);
659 // this is to catch all plain \n instances and
660 // replace them with \r\n. All newlines were converted
661 // into just \n inside the compose.php file.
662 $body = ereg_replace("\n", "\r\n", $body);
665 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
667 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
670 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
671 sqimap_append ($imap_stream, $sent_folder, $length);
672 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
673 writeBody ($imap_stream, $body);
674 sqimap_append_done ($imap_stream);
676 sqimap_logout($imap_stream);
677 // Delete the files uploaded for attaching (if any).
678 // only if $length != 0 (if there was no error)
685 function createPriorityHeaders($prio) {
686 $prio_headers = Array();
687 $prio_headers["X-Priority"] = $prio;
690 case 1: $prio_headers["Importance"] = "High";
691 $prio_headers["X-MSMail-Priority"] = "High";
694 case 3: $prio_headers["Importance"] = "Normal";
695 $prio_headers["X-MSMail-Priority"] = "Normal";
699 $prio_headers["Importance"] = "Low";
700 $prio_headers["X-MSMail-Priority"] = "Low";
703 return $prio_headers;