4 ** This contains all the functions needed to send messages through
5 ** an smtp server or sendmail.
10 // This should most probably go to some initialization...
11 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
12 $popuser = $usernamedata[1];
13 $domain = $usernamedata[2];
18 // We need domain for smtp
20 $domain = getenv("HOSTNAME");
22 // Returns true only if this message is multipart
23 function isMultipart () {
26 if (count($attachments)>0)
32 // Attach the files that are due to be attached
33 function attachFiles ($fp) {
34 global $attachments, $attachment_dir;
40 while (list($localname, $remotename) = each($attachments)) {
41 // This is to make sure noone is giving a filename in another
43 $localname = ereg_replace ("\\/", "", $localname);
45 $fileinfo = fopen ($attachment_dir.$localname.".info", "r");
46 $filetype = fgets ($fileinfo, 8192);
48 $filetype = trim ($filetype);
50 $filetype = "application/octet-stream";
52 $header = "--".mimeBoundary()."\r\n";
53 $header .= "Content-Type: $filetype\r\n";
54 $header .= "Content-Disposition: attachment; filename=\"$remotename\"\r\n";
55 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
57 $length +
= strlen($header);
59 $file = fopen ($attachment_dir.$localname, "r");
60 while ($tmp = fread($file, 570)) {
61 $encoded = chunk_split(base64_encode($tmp));
62 $length +
= strlen($encoded);
63 fputs ($fp, $encoded);
72 // Delete files that are uploaded for attaching
73 function deleteAttachments() {
74 global $attachments, $attachment_dir;
78 while (list($localname, $remotename) = each($attachments)) {
79 if (!ereg ("\\/", $localname)) {
80 unlink ($attachment_dir.$localname);
81 unlink ($attachment_dir.$localname.".info");
87 // Return a nice MIME-boundary
88 function mimeBoundary () {
89 static $mimeBoundaryString;
91 if ($mimeBoundaryString == "") {
92 $mimeBoundaryString = GenerateRandomString(70, '\'()+,-./:=?_', 7);
95 return $mimeBoundaryString;
98 /* Time offset for correct timezone */
99 function timezone () {
100 $diff_second = date("Z");
102 $diff_second = - $diff_second;
103 if ($diff_second > 0)
108 $diff_second = abs($diff_second);
110 $diff_hour = floor ($diff_second / 3600);
111 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
113 $zonename = "(".strftime("%Z").")";
114 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
118 /* Print all the needed RFC822 headers */
119 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
120 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
121 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
122 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
125 // Storing the header to make sure the header is the same
126 // everytime the header is printed.
127 static $header, $headerlength;
130 $to = parseAddrs($t);
131 $cc = parseAddrs($c);
132 $bcc = parseAddrs($b);
133 $reply_to = getPref($data_dir, $username, "reply_to");
134 $from = getPref($data_dir, $username, "full_name");
135 $from_addr = getPref($data_dir, $username, "email_address");
137 if ($from_addr == "")
138 $from_addr = $popuser."@".$domain;
140 $to_list = getLineOfAddrs($to);
141 $cc_list = getLineOfAddrs($cc);
142 $bcc_list = getLineOfAddrs($bcc);
144 /* Encoding 8-bit characters and making from line */
145 $subject = sqStripSlashes(encodeHeader($subject));
147 $from = "<$from_addr>";
149 $from = "\"" . encodeHeader($from) . "\" <$from_addr>";
151 /* This creates an RFC 822 date */
152 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
154 /* Create a message-id */
155 $message_id = "<" . $REMOTE_PORT . "." . $REMOTE_ADDR . ".";
156 $message_id .= time() . ".squirrel@" . $SERVER_NAME .">";
158 /* Make an RFC822 Received: line */
159 if (isset($REMOTE_HOST))
160 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
162 $received_from = $REMOTE_ADDR;
164 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
165 if ($HTTP_X_FORWARDED_FOR == "")
166 $HTTP_X_FORWARDED_FOR = "unknown";
167 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
170 $header = "Received: from $received_from\r\n";
171 $header .= " (SquirrelMail authenticated user $username)\r\n";
172 $header .= " by $SERVER_NAME with HTTP;\r\n";
173 $header .= " $date\r\n";
175 /* Insert the rest of the header fields */
176 $header .= "Message-ID: $message_id\r\n";
177 $header .= "Date: $date\r\n";
178 $header .= "Subject: $subject\r\n";
179 $header .= "From: $from\r\n";
180 $header .= "To: $to_list \r\n"; // Who it's TO
182 /* Insert headers from the $more_headers array */
183 if(is_array($more_headers)) {
184 reset($more_headers);
185 while(list($h_name, $h_val) = each($more_headers)) {
186 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
191 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
195 $header .= "Reply-To: $reply_to\r\n";
199 // BCCs is removed from header by sendmail
200 $header .= "Bcc: $bcc_list\r\n";
204 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
207 $header .= "MIME-Version: 1.0\r\n";
210 $header .= "Content-Type: multipart/mixed; boundary=\"";
211 $header .= mimeBoundary();
214 if ($default_charset != "")
215 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
217 $header .= "Content-Type: text/plain;\r\n";
218 $header .= "Content-Transfer-Encoding: 8bit\r\n";
220 $header .= "\r\n"; // One blank line to separate header and body
222 $headerlength = strlen($header);
226 fputs ($fp, $header);
228 return $headerlength;
232 function writeBody ($fp, $passedBody) {
233 global $default_charset;
235 $attachmentlength = 0;
238 $body = "--".mimeBoundary()."\r\n";
240 if ($default_charset != "")
241 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
243 $body .= "Content-Type: text/plain\r\n";
245 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
246 $body .= sqStripSlashes($passedBody) . "\r\n";
249 $attachmentlength = attachFiles($fp);
251 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
252 fputs ($fp, $postbody);
254 $body = sqStripSlashes($passedBody) . "\r\n";
257 fputs ($fp, $postbody);
260 return (strlen($body) +
strlen($postbody) +
$attachmentlength);
263 // Send mail using the sendmail command
264 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
265 global $sendmail_path, $popuser, $username, $domain;
267 // Build envelope sender address. Make sure it doesn't contain
268 // spaces or other "weird" chars that would allow a user to
269 // exploit the shell/pipe it is used in.
270 $envelopefrom = "$popuser@$domain";
271 $envelopefrom = ereg_replace("[[:blank:]]","", $envelopefrom);
272 $envelopefrom = ereg_replace("[[:space:]]","", $envelopefrom);
273 $envelopefrom = ereg_replace("[[:cntrl:]]","", $envelopefrom);
275 // open pipe to sendmail
276 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
278 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
279 $bodylength = writeBody($fp, $body);
283 return ($headerlength +
$bodylength);
286 function smtpReadData($smtpConnection) {
287 $read = fgets($smtpConnection, 1024);
291 $data[$counter] = $read;
292 $read = fgets($smtpConnection, 1024);
297 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
298 global $username, $popuser, $domain, $version, $smtpServerAddress, $smtpPort,
301 $to = parseAddrs($t);
302 $cc = parseAddrs($c);
303 $bcc = parseAddrs($b);
304 $from_addr = getPref($data_dir, $username, "email_address");
307 $from_addr = "$popuser@$domain";
309 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
310 if (!$smtpConnection) {
311 echo "Error connecting to SMTP Server.<br>";
312 echo "$errorNumber : $errorString<br>";
315 $tmp = fgets($smtpConnection, 1024);
316 errorCheck($tmp, $smtpConnection);
318 $to_list = getLineOfAddrs($to);
319 $cc_list = getLineOfAddrs($cc);
321 /** Lets introduce ourselves */
322 fputs($smtpConnection, "HELO $domain\r\n");
323 $tmp = fgets($smtpConnection, 1024);
324 errorCheck($tmp, $smtpConnection);
326 /** Ok, who is sending the message? */
327 fputs($smtpConnection, "MAIL FROM:<$from_addr>\r\n");
328 $tmp = fgets($smtpConnection, 1024);
329 errorCheck($tmp, $smtpConnection);
331 /** send who the recipients are */
332 for ($i = 0; $i < count($to); $i++
) {
333 fputs($smtpConnection, "RCPT TO:<$to[$i]>\r\n");
334 $tmp = fgets($smtpConnection, 1024);
335 errorCheck($tmp, $smtpConnection);
337 for ($i = 0; $i < count($cc); $i++
) {
338 fputs($smtpConnection, "RCPT TO:<$cc[$i]>\r\n");
339 $tmp = fgets($smtpConnection, 1024);
340 errorCheck($tmp, $smtpConnection);
342 for ($i = 0; $i < count($bcc); $i++
) {
343 fputs($smtpConnection, "RCPT TO:<$bcc[$i]>\r\n");
344 $tmp = fgets($smtpConnection, 1024);
345 errorCheck($tmp, $smtpConnection);
348 /** Lets start sending the actual message */
349 fputs($smtpConnection, "DATA\r\n");
350 $tmp = fgets($smtpConnection, 1024);
351 errorCheck($tmp, $smtpConnection);
354 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
355 $bodylength = writeBody($smtpConnection, $body);
357 fputs($smtpConnection, ".\r\n"); // end the DATA part
358 $tmp = fgets($smtpConnection, 1024);
359 $num = errorCheck($tmp, $smtpConnection);
361 $tmp = nl2br(htmlspecialchars($tmp));
362 echo "ERROR<BR>Message not sent!<BR>Reason given: $tmp<BR></BODY></HTML>";
365 fputs($smtpConnection, "QUIT\r\n"); // log off
367 fclose($smtpConnection);
369 return ($headerlength +
$bodylength);
373 function errorCheck($line, $smtpConnection) {
374 global $page_header_php;
376 if (!isset($page_header_php)) {
377 include "../functions/page_header.php";
380 // Read new lines on a multiline response
382 while(ereg("^[0-9]+-", $line)) {
383 $line = fgets($smtpConnection, 1024);
390 $err_num = substr($line, 0, strpos($line, " "));
392 case 500: $message = "Syntax error; command not recognized";
395 case 501: $message = "Syntax error in parameters or arguments";
398 case 502: $message = "Command not implemented";
401 case 503: $message = "Bad sequence of commands";
404 case 504: $message = "Command parameter not implemented";
409 case 211: $message = "System status, or system help reply";
412 case 214: $message = "Help message";
417 case 220: $message = "Service ready";
420 case 221: $message = "Service closing transmission channel";
423 case 421: $message = "Service not available, closing chanel";
428 case 250: $message = "Requested mail action okay, completed";
431 case 251: $message = "User not local; will forward";
434 case 450: $message = "Requested mail action not taken: mailbox unavailable";
437 case 550: $message = "Requested action not taken: mailbox unavailable";
440 case 451: $message = "Requested action aborted: error in processing";
443 case 551: $message = "User not local; please try forwarding";
446 case 452: $message = "Requested action not taken: insufficient system storage";
449 case 552: $message = "Requested mail action aborted: exceeding storage allocation";
452 case 553: $message = "Requested action not taken: mailbox name not allowed";
455 case 354: $message = "Start mail input; end with .";
458 case 554: $message = "Transaction failed";
461 default: $message = "Unknown response: ". nl2br(htmlspecialchars($lines));
468 displayPageHeader($color, "None");
470 echo "<br><b><font color=\"$color[1]\">ERROR</font></b><br><br>";
471 echo " <B>Error Number: </B>$err_num<BR>";
472 echo " <B>Reason: </B>$message<BR>";
473 $lines = nl2br(htmlspecialchars($lines));
474 echo "<B>Server Response: </B>$lines<BR>";
475 echo "<BR>MAIL NOT SENT";
476 echo "</TT></BODY></HTML>";
482 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
483 global $useSendmail, $msg_id, $is_reply, $mailbox;
484 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
485 $more_headers = Array();
487 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
490 sqimap_mailbox_select ($imap_stream, $mailbox);
491 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, "Answered");
493 // Insert In-Reply-To and References headers if the
494 // message-id of the message we reply to is set (longer than "<>")
495 // The References header should really be the old Referenced header
496 // with the message ID appended, but it can be only the message ID too.
497 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
498 if(strlen($hdr->message_id
) > 2) {
499 $more_headers["In-Reply-To"] = $hdr->message_id
;
500 $more_headers["References"] = $hdr->message_id
;
502 sqimap_mailbox_close($imap_stream);
506 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
508 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
511 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
512 sqimap_append ($imap_stream, $sent_folder, $length);
513 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
514 writeBody ($imap_stream, $body);
515 sqimap_append_done ($imap_stream);
517 sqimap_logout($imap_stream);
518 // Delete the files uploaded for attaching (if any).