4 ** This contains all the functions needed to send messages through
5 ** an smtp server or sendmail.
10 // Returns true only if this message is multipart
11 function isMultipart () {
14 if (count($attachments)>0)
20 // Attach the files that are due to be attached
21 function attachFiles ($fp) {
22 global $attachments, $attachment_dir;
28 while (list($localname, $remotename) = each($attachments)) {
29 // This is to make sure noone is giving a filename in another
31 $localname = ereg_replace ("\\/", "", $localname);
33 $fileinfo = fopen ($attachment_dir.$localname.".info", "r");
34 $filetype = fgets ($fileinfo, 8192);
36 $filetype = trim ($filetype);
38 $filetype = "application/octet-stream";
40 $header = "--".mimeBoundary()."\r\n";
41 $header .= "Content-Type: $filetype\r\n";
42 $header .= "Content-Disposition: attachment; filename=\"$remotename\"\r\n";
43 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
45 $length +
= strlen($header);
47 $file = fopen ($attachment_dir.$localname, "r");
48 while ($tmp = fread($file, 570)) {
49 $encoded = chunk_split(base64_encode($tmp));
50 $length +
= strlen($encoded);
51 fputs ($fp, $encoded);
60 // Delete files that are uploaded for attaching
61 function deleteAttachments() {
62 global $attachments, $attachment_dir;
66 while (list($localname, $remotename) = each($attachments)) {
67 if (!ereg ("\\/", $localname)) {
68 unlink ($attachment_dir.$localname);
69 unlink ($attachment_dir.$localname.".info");
75 // Return a nice MIME-boundary
76 function mimeBoundary () {
77 static $mimeBoundaryString;
79 if ($mimeBoundaryString == "") {
80 sq_mt_randomize(); // Initialize the random number generator
81 // Use all allowed chars besides space.
82 $Chrs = '\'()+,-./0123456789:=?ABCDEFGHIJKLMNOP' .
83 'QRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
84 // Create a LONG boundary to ensure no duplicates
85 while (strlen($mimeBoundaryString) < 70) {
86 $mimeBoundaryString .= $Chrs[mt_rand(0, strlen($Chrs))];
90 return $mimeBoundaryString;
93 /* Time offset for correct timezone */
94 function timezone () {
95 $diff_second = date("Z");
101 $diff_second = abs($diff_second);
103 $diff_hour = floor ($diff_second / 3600);
104 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
106 $zonename = "(".strftime("%Z").")";
107 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
111 /* Print all the needed RFC822 headers */
112 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
113 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
114 global $data_dir, $username, $domain, $version, $useSendmail;
115 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
118 // Storing the header to make sure the header is the same
119 // everytime the header is printed.
120 static $header, $headerlength;
123 $to = parseAddrs($t);
124 $cc = parseAddrs($c);
125 $bcc = parseAddrs($b);
126 $reply_to = getPref($data_dir, $username, "reply_to");
127 $from = getPref($data_dir, $username, "full_name");
128 $from_addr = getPref($data_dir, $username, "email_address");
130 if ($from_addr == "")
131 $from_addr = "$username@$domain";
133 $to_list = getLineOfAddrs($to);
134 $cc_list = getLineOfAddrs($cc);
135 $bcc_list = getLineOfAddrs($bcc);
137 /* Encoding 8-bit characters and making from line */
138 $subject = sqStripSlashes(encodeHeader($subject));
140 $from = "<$from_addr>";
142 $from = "\"" . encodeHeader($from) . "\" <$from_addr>";
144 /* This creates an RFC 822 date */
145 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
147 /* Create a message-id */
148 $message_id = "<" . $REMOTE_PORT . "." . $REMOTE_ADDR . ".";
149 $message_id .= time() . ".squirrel@" . $SERVER_NAME .">";
151 /* Make an RFC822 Received: line */
152 if (isset($REMOTE_HOST))
153 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
155 $received_from = $REMOTE_ADDR;
157 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
158 if ($HTTP_X_FORWARDED_FOR == "")
159 $HTTP_X_FORWARDED_FOR = "unknown";
160 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
163 $header = "Received: from $received_from\r\n";
164 $header .= " (SquirrelMail authenticated user $username)\r\n";
165 $header .= " by $SERVER_NAME with HTTP;\r\n";
166 $header .= " $date\r\n";
168 /* Insert the rest of the header fields */
169 $header .= "Message-ID: $message_id\r\n";
170 $header .= "Date: $date\r\n";
171 $header .= "Subject: $subject\r\n";
172 $header .= "From: $from\r\n";
173 $header .= "To: $to_list \r\n"; // Who it's TO
175 /* Insert headers from the $more_headers array */
176 if(is_array($more_headers)) {
177 reset($more_headers);
178 while(list($h_name, $h_val) = each($more_headers)) {
179 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
184 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
188 $header .= "Reply-To: $reply_to\r\n";
192 // BCCs is removed from header by sendmail
193 $header .= "Bcc: $bcc_list\r\n";
197 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
200 $header .= "MIME-Version: 1.0\r\n";
203 $header .= "Content-Type: multipart/mixed; boundary=\"";
204 $header .= mimeBoundary();
207 if ($default_charset != "")
208 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
210 $header .= "Content-Type: text/plain;\r\n";
211 $header .= "Content-Transfer-Encoding: 8bit\r\n";
213 $header .= "\r\n"; // One blank line to separate header and body
215 $headerlength = strlen($header);
219 fputs ($fp, $header);
221 return $headerlength;
225 function writeBody ($fp, $passedBody) {
226 global $default_charset;
228 $attachmentlength = 0;
231 $body = "--".mimeBoundary()."\r\n";
233 if ($default_charset != "")
234 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
236 $body .= "Content-Type: text/plain\r\n";
238 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
239 $body .= sqStripSlashes($passedBody) . "\r\n";
242 $attachmentlength = attachFiles($fp);
244 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
245 fputs ($fp, $postbody);
247 $body = sqStripSlashes($passedBody) . "\r\n";
250 fputs ($fp, $postbody);
253 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
256 // Send mail using the sendmail command
257 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
258 global $sendmail_path, $username, $domain;
260 // Build envelope sender address. Make sure it doesn't contain
261 // spaces or other "weird" chars that would allow a user to
262 // exploit the shell/pipe it is used in.
263 $envelopefrom = "$username@$domain";
264 $envelopefrom = ereg_replace("[[:blank:]]","", $envelopefrom);
265 $envelopefrom = ereg_replace("[[:space:]]","", $envelopefrom);
266 $envelopefrom = ereg_replace("[[:cntrl:]]","", $envelopefrom);
268 // open pipe to sendmail
269 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
271 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
272 $bodylength = writeBody($fp, $body);
276 return ($headerlength +
$bodylength);
279 function smtpReadData($smtpConnection) {
280 $read = fgets($smtpConnection, 1024);
284 $data[$counter] = $read;
285 $read = fgets($smtpConnection, 1024);
290 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
291 global $username, $domain, $version, $smtpServerAddress, $smtpPort,
294 $to = parseAddrs($t);
295 $cc = parseAddrs($c);
296 $bcc = parseAddrs($b);
297 $from_addr = getPref($data_dir, $username, "email_address");
301 * A patch from Bill Thousand <billyt@claritytech.com>
303 * "I don't know if anyone else needs this or not, but it totally makes squirrelmail usable for us.
304 * This quick patch checks the username and from address for the domain information. We use
305 * a virtual domain patch for our imap server that allows multiple domains by using username@domain.com
306 * as the login username."
308 if ($from_addr == "") {
309 if (strstr($username, "@")) {
310 $from_addr = $username;
311 $address_pieces = explode("@",$username);
312 $domain = $address_pieces[1];
314 $from_addr = "$username@$domain";
317 // If the From Address is specified, use the domain in the from
318 // address if it's there.
319 if (strstr($from_addr, "@")) {
320 $address_pieces = explode("@", $from_addr);
321 $domain = $address_pieces[1];
325 * End patch from Bill Thousand
329 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
330 if (!$smtpConnection) {
331 echo "Error connecting to SMTP Server.<br>";
332 echo "$errorNumber : $errorString<br>";
335 $tmp = fgets($smtpConnection, 1024);
336 errorCheck($tmp, $smtpConnection);
338 $to_list = getLineOfAddrs($to);
339 $cc_list = getLineOfAddrs($cc);
341 /** Lets introduce ourselves */
342 fputs($smtpConnection, "HELO $domain\r\n");
343 $tmp = fgets($smtpConnection, 1024);
344 errorCheck($tmp, $smtpConnection);
346 /** Ok, who is sending the message? */
347 fputs($smtpConnection, "MAIL FROM:<$from_addr>\r\n");
348 $tmp = fgets($smtpConnection, 1024);
349 errorCheck($tmp, $smtpConnection);
351 /** send who the recipients are */
352 for ($i = 0; $i < count($to); $i++
) {
353 fputs($smtpConnection, "RCPT TO:<$to[$i]>\r\n");
354 $tmp = fgets($smtpConnection, 1024);
355 errorCheck($tmp, $smtpConnection);
357 for ($i = 0; $i < count($cc); $i++
) {
358 fputs($smtpConnection, "RCPT TO:<$cc[$i]>\r\n");
359 $tmp = fgets($smtpConnection, 1024);
360 errorCheck($tmp, $smtpConnection);
362 for ($i = 0; $i < count($bcc); $i++
) {
363 fputs($smtpConnection, "RCPT TO:<$bcc[$i]>\r\n");
364 $tmp = fgets($smtpConnection, 1024);
365 errorCheck($tmp, $smtpConnection);
368 /** Lets start sending the actual message */
369 fputs($smtpConnection, "DATA\r\n");
370 $tmp = fgets($smtpConnection, 1024);
371 errorCheck($tmp, $smtpConnection);
374 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
375 $bodylength = writeBody($smtpConnection, $body);
377 fputs($smtpConnection, ".\r\n"); // end the DATA part
378 $tmp = fgets($smtpConnection, 1024);
379 $num = errorCheck($tmp, $smtpConnection);
381 $tmp = nl2br(htmlspecialchars($tmp));
382 echo "ERROR<BR>Message not sent!<BR>Reason given: $tmp<BR></BODY></HTML>";
385 fputs($smtpConnection, "QUIT\r\n"); // log off
387 fclose($smtpConnection);
389 return ($headerlength +
$bodylength);
393 function errorCheck($line, $smtpConnection) {
394 global $page_header_php;
396 if (!isset($page_header_php)) {
397 include "../functions/page_header.php";
400 // Read new lines on a multiline response
402 while(ereg("^[0-9]+-", $line)) {
403 $line = fgets($smtpConnection, 1024);
410 $err_num = substr($line, 0, strpos($line, " "));
412 case 500: $message = "Syntax error; command not recognized";
415 case 501: $message = "Syntax error in parameters or arguments";
418 case 502: $message = "Command not implemented";
421 case 503: $message = "Bad sequence of commands";
424 case 504: $message = "Command parameter not implemented";
429 case 211: $message = "System status, or system help reply";
432 case 214: $message = "Help message";
437 case 220: $message = "Service ready";
440 case 221: $message = "Service closing transmission channel";
443 case 421: $message = "Service not available, closing chanel";
448 case 250: $message = "Requested mail action okay, completed";
451 case 251: $message = "User not local; will forward";
454 case 450: $message = "Requested mail action not taken: mailbox unavailable";
457 case 550: $message = "Requested action not taken: mailbox unavailable";
460 case 451: $message = "Requested action aborted: error in processing";
463 case 551: $message = "User not local; please try forwarding";
466 case 452: $message = "Requested action not taken: insufficient system storage";
469 case 552: $message = "Requested mail action aborted: exceeding storage allocation";
472 case 553: $message = "Requested action not taken: mailbox name not allowed";
475 case 354: $message = "Start mail input; end with .";
478 case 554: $message = "Transaction failed";
481 default: $message = "Unknown response: ". nl2br(htmlspecialchars($lines));
488 displayPageHeader($color, "None");
490 echo "<br><b><font color=\"$color[1]\">ERROR</font></b><br><br>";
491 echo " <B>Error Number: </B>$err_num<BR>";
492 echo " <B>Reason: </B>$message<BR>";
493 $lines = nl2br(htmlspecialchars($lines));
494 echo "<B>Server Response: </B>$lines<BR>";
495 echo "<BR>MAIL NOT SENT";
496 echo "</TT></BODY></HTML>";
502 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
503 global $useSendmail, $msg_id, $is_reply, $mailbox;
504 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
505 $more_headers = Array();
507 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
510 sqimap_mailbox_select ($imap_stream, $mailbox);
511 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, "Answered");
513 // Insert In-Reply-To and References headers if the
514 // message-id of the message we reply to is set (longer than "<>")
515 // The References header should really be the old Referenced header
516 // with the message ID appended, but it can be only the message ID too.
517 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
518 if(strlen($hdr->message_id
) > 2) {
519 $more_headers["In-Reply-To"] = $hdr->message_id
;
520 $more_headers["References"] = $hdr->message_id
;
522 sqimap_mailbox_close($imap_stream);
525 if ($useSendmail==true) {
526 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
528 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
531 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
532 sqimap_append ($imap_stream, $sent_folder, $length);
533 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
534 writeBody ($imap_stream, $body);
535 sqimap_append_done ($imap_stream);
537 sqimap_logout($imap_stream);
538 // Delete the files uploaded for attaching (if any).