smtp.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. <?php
  2. /** smtp.php
  3. **
  4. ** This contains all the functions needed to send messages through
  5. ** an smtp server or sendmail.
  6. **/
  7. $smtp_php = true;
  8. // Returns true only if this message is multipart
  9. function isMultipart () {
  10. global $attachments;
  11. if (count($attachments)>0)
  12. return true;
  13. else
  14. return false;
  15. }
  16. // Attach the files that are due to be attached
  17. function attachFiles ($fp) {
  18. global $attachments, $attachment_dir;
  19. $length = 0;
  20. if (isMultipart()) {
  21. reset($attachments);
  22. while (list($localname, $remotename) = each($attachments)) {
  23. // This is to make sure noone is giving a filename in another
  24. // directory
  25. $localname = ereg_replace ("\\/", "", $localname);
  26. $fileinfo = fopen ($attachment_dir.$localname.".info", "r");
  27. $filetype = fgets ($fileinfo, 8192);
  28. fclose ($fileinfo);
  29. $filetype = trim ($filetype);
  30. if ($filetype=="")
  31. $filetype = "application/octet-stream";
  32. $header = "--".mimeBoundary()."\r\n";
  33. $header .= "Content-Type: $filetype\r\n";
  34. $header .= "Content-Disposition: attachment; filename=\"$remotename\"\r\n";
  35. $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
  36. fputs ($fp, $header);
  37. $length += strlen($header);
  38. $file = fopen ($attachment_dir.$localname, "r");
  39. while ($tmp = fread($file, 570)) {
  40. $encoded = chunk_split(base64_encode($tmp));
  41. $length += strlen($encoded);
  42. fputs ($fp, $encoded);
  43. }
  44. fclose ($file);
  45. }
  46. }
  47. return $length;
  48. }
  49. // Delete files that are uploaded for attaching
  50. function deleteAttachments() {
  51. global $attachments, $attachment_dir;
  52. if (isMultipart()) {
  53. reset($attachments);
  54. while (list($localname, $remotename) = each($attachments)) {
  55. if (!ereg ("\\/", $localname)) {
  56. unlink ($attachment_dir.$localname);
  57. unlink ($attachment_dir.$localname.".info");
  58. }
  59. }
  60. }
  61. }
  62. // Return a nice MIME-boundary
  63. function mimeBoundary () {
  64. global $version, $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
  65. static $mimeBoundaryString;
  66. if ($mimeBoundaryString == "") {
  67. $temp = "SquirrelMail".$version.$REMOTE_ADDR.$SERVER_NAME.
  68. $REMOTE_PORT;
  69. $mimeBoundaryString = "=-_+".substr(md5($temp),1,20);
  70. }
  71. return $mimeBoundaryString;
  72. }
  73. /* Time offset for correct timezone */
  74. function timezone () {
  75. $diff_second = date("Z");
  76. if ($diff_second > 0)
  77. $sign = "+";
  78. else
  79. $sign = "-";
  80. $diff_second = abs($diff_second);
  81. $diff_hour = floor ($diff_second / 3600);
  82. $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
  83. $zonename = "(".strftime("%Z").")";
  84. $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
  85. return ($result);
  86. }
  87. /* Print all the needed RFC822 headers */
  88. function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
  89. global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
  90. global $data_dir, $username, $domain, $version, $useSendmail;
  91. global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
  92. global $REMOTE_HOST;
  93. // Storing the header to make sure the header is the same
  94. // everytime the header is printed.
  95. static $header, $headerlength;
  96. if ($header == "") {
  97. $to = parseAddrs($t);
  98. $cc = parseAddrs($c);
  99. $bcc = parseAddrs($b);
  100. $reply_to = getPref($data_dir, $username, "reply_to");
  101. $from = getPref($data_dir, $username, "full_name");
  102. $from_addr = getPref($data_dir, $username, "email_address");
  103. if ($from_addr == "")
  104. $from_addr = "$username@$domain";
  105. $to_list = getLineOfAddrs($to);
  106. $cc_list = getLineOfAddrs($cc);
  107. $bcc_list = getLineOfAddrs($bcc);
  108. /* Encoding 8-bit characters and making from line */
  109. $subject = sqStripSlashes(encodeHeader($subject));
  110. if ($from == "")
  111. $from = "<$from_addr>";
  112. else
  113. $from = "\"" . encodeHeader($from) . "\" <$from_addr>";
  114. /* This creates an RFC 822 date */
  115. $date = date("D, j M Y H:i:s ", mktime()) . timezone();
  116. /* Create a message-id */
  117. $message_id = "<" . $REMOTE_PORT . "." . $REMOTE_ADDR . ".";
  118. $message_id .= time() . ".squirrel@" . $SERVER_NAME .">";
  119. /* Make an RFC822 Received: line */
  120. if (isset($REMOTE_HOST))
  121. $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
  122. else
  123. $received_from = $REMOTE_ADDR;
  124. if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
  125. if ($HTTP_X_FORWARDED_FOR == "")
  126. $HTTP_X_FORWARDED_FOR = "unknown";
  127. $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
  128. }
  129. $header = "Received: from $received_from\r\n";
  130. $header .= " (SquirrelMail authenticated user $username)\r\n";
  131. $header .= " by $SERVER_NAME with HTTP;\r\n";
  132. $header .= " $date\r\n";
  133. /* Insert the rest of the header fields */
  134. $header .= "Message-ID: $message_id\r\n";
  135. $header .= "Date: $date\r\n";
  136. $header .= "Subject: $subject\r\n";
  137. $header .= "From: $from\r\n";
  138. $header .= "To: $to_list \r\n"; // Who it's TO
  139. /* Insert headers from the $more_headers array */
  140. if(is_array($more_headers)) {
  141. reset($more_headers);
  142. while(list($h_name, $h_val) = each($more_headers)) {
  143. $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
  144. }
  145. }
  146. if ($cc_list) {
  147. $header .= "Cc: $cc_list\r\n"; // Who the CCs are
  148. }
  149. if ($reply_to != "")
  150. $header .= "Reply-To: $reply_to\r\n";
  151. if ($useSendmail) {
  152. if ($bcc_list) {
  153. // BCCs is removed from header by sendmail
  154. $header .= "Bcc: $bcc_list\r\n";
  155. }
  156. }
  157. $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
  158. // Do the MIME-stuff
  159. $header .= "MIME-Version: 1.0\r\n";
  160. if (isMultipart()) {
  161. $header .= "Content-Type: multipart/mixed; boundary=\"";
  162. $header .= mimeBoundary();
  163. $header .= "\"\r\n";
  164. } else {
  165. if ($default_charset != "")
  166. $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
  167. else
  168. $header .= "Content-Type: text/plain;\r\n";
  169. $header .= "Content-Transfer-Encoding: 8bit\r\n";
  170. }
  171. $header .= "\r\n"; // One blank line to separate header and body
  172. $headerlength = strlen($header);
  173. }
  174. // Write the header
  175. fputs ($fp, $header);
  176. return $headerlength;
  177. }
  178. // Send the body
  179. function writeBody ($fp, $passedBody) {
  180. global $default_charset;
  181. $attachmentlength = 0;
  182. if (isMultipart()) {
  183. $body = "--".mimeBoundary()."\r\n";
  184. if ($default_charset != "")
  185. $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
  186. else
  187. $body .= "Content-Type: text/plain\r\n";
  188. $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
  189. $body .= sqStripSlashes($passedBody) . "\r\n";
  190. fputs ($fp, $body);
  191. $attachmentlength = attachFiles($fp);
  192. $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
  193. fputs ($fp, $postbody);
  194. } else {
  195. $body = sqStripSlashes($passedBody) . "\r\n";
  196. fputs ($fp, $body);
  197. $postbody = "\r\n";
  198. fputs ($fp, $postbody);
  199. }
  200. return (strlen($body) + strlen($postbody) + $attachmentlength);
  201. }
  202. // Send mail using the sendmail command
  203. function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
  204. global $sendmail_path, $username, $domain;
  205. // Build envelope sender address. Make sure it doesn't contain
  206. // spaces or other "weird" chars that would allow a user to
  207. // exploit the shell/pipe it is used in.
  208. $envelopefrom = "$username@$domain";
  209. $envelopefrom = ereg_replace("[[:blank:]]","", $envelopefrom);
  210. $envelopefrom = ereg_replace("[[:space:]]","", $envelopefrom);
  211. $envelopefrom = ereg_replace("[[:cntrl:]]","", $envelopefrom);
  212. // open pipe to sendmail
  213. $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
  214. $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
  215. $bodylength = writeBody($fp, $body);
  216. pclose($fp);
  217. return ($headerlength + $bodylength);
  218. }
  219. function smtpReadData($smtpConnection) {
  220. $read = fgets($smtpConnection, 1024);
  221. $counter = 0;
  222. while ($read) {
  223. echo $read . "<BR>";
  224. $data[$counter] = $read;
  225. $read = fgets($smtpConnection, 1024);
  226. $counter++;
  227. }
  228. }
  229. function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
  230. global $username, $domain, $version, $smtpServerAddress, $smtpPort,
  231. $data_dir, $color;
  232. $to = parseAddrs($t);
  233. $cc = parseAddrs($c);
  234. $bcc = parseAddrs($b);
  235. $from_addr = getPref($data_dir, $username, "email_address");
  236. /*
  237. * A patch from Bill Thousand <billyt@claritytech.com>
  238. *
  239. * "I don't know if anyone else needs this or not, but it totally makes squirrelmail usable for us.
  240. * This quick patch checks the username and from address for the domain information. We use
  241. * a virtual domain patch for our imap server that allows multiple domains by using username@domain.com
  242. * as the login username."
  243. */
  244. if ($from_addr == "") {
  245. if (strstr($username, "@")) {
  246. $from_addr = $username;
  247. $address_pieces = explode("@",$username);
  248. $domain = $address_pieces[1];
  249. } else {
  250. $from_addr = "$username@$domain";
  251. }
  252. } else {
  253. // If the From Address is specified, use the domain in the from
  254. // address if it's there.
  255. if (strstr($from_addr, "@")) {
  256. $address_pieces = explode("@", $from_addr);
  257. $domain = $address_pieces[1];
  258. }
  259. }
  260. /*
  261. * End patch from Bill Thousand
  262. */
  263. $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
  264. if (!$smtpConnection) {
  265. echo "Error connecting to SMTP Server.<br>";
  266. echo "$errorNumber : $errorString<br>";
  267. exit;
  268. }
  269. $tmp = fgets($smtpConnection, 1024);
  270. errorCheck($tmp, $smtpConnection);
  271. $to_list = getLineOfAddrs($to);
  272. $cc_list = getLineOfAddrs($cc);
  273. /** Lets introduce ourselves */
  274. fputs($smtpConnection, "HELO $domain\r\n");
  275. $tmp = fgets($smtpConnection, 1024);
  276. errorCheck($tmp, $smtpConnection);
  277. /** Ok, who is sending the message? */
  278. fputs($smtpConnection, "MAIL FROM:<$from_addr>\r\n");
  279. $tmp = fgets($smtpConnection, 1024);
  280. errorCheck($tmp, $smtpConnection);
  281. /** send who the recipients are */
  282. for ($i = 0; $i < count($to); $i++) {
  283. fputs($smtpConnection, "RCPT TO:<$to[$i]>\r\n");
  284. $tmp = fgets($smtpConnection, 1024);
  285. errorCheck($tmp, $smtpConnection);
  286. }
  287. for ($i = 0; $i < count($cc); $i++) {
  288. fputs($smtpConnection, "RCPT TO:<$cc[$i]>\r\n");
  289. $tmp = fgets($smtpConnection, 1024);
  290. errorCheck($tmp, $smtpConnection);
  291. }
  292. for ($i = 0; $i < count($bcc); $i++) {
  293. fputs($smtpConnection, "RCPT TO:<$bcc[$i]>\r\n");
  294. $tmp = fgets($smtpConnection, 1024);
  295. errorCheck($tmp, $smtpConnection);
  296. }
  297. /** Lets start sending the actual message */
  298. fputs($smtpConnection, "DATA\r\n");
  299. $tmp = fgets($smtpConnection, 1024);
  300. errorCheck($tmp, $smtpConnection);
  301. // Send the message
  302. $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
  303. $bodylength = writeBody($smtpConnection, $body);
  304. fputs($smtpConnection, ".\r\n"); // end the DATA part
  305. $tmp = fgets($smtpConnection, 1024);
  306. $num = errorCheck($tmp, $smtpConnection);
  307. if ($num != 250) {
  308. $tmp = nl2br(htmlspecialchars($tmp));
  309. echo "ERROR<BR>Message not sent!<BR>Reason given: $tmp<BR></BODY></HTML>";
  310. }
  311. fputs($smtpConnection, "QUIT\r\n"); // log off
  312. fclose($smtpConnection);
  313. return ($headerlength + $bodylength);
  314. }
  315. function errorCheck($line, $smtpConnection) {
  316. global $page_header_php;
  317. global $color;
  318. if (!isset($page_header_php)) {
  319. include "../functions/page_header.php";
  320. }
  321. // Read new lines on a multiline response
  322. $lines = $line;
  323. while(ereg("^[0-9]+-", $line)) {
  324. $line = fgets($smtpConnection, 1024);
  325. $lines .= $line;
  326. }
  327. // Status: 0 = fatal
  328. // 5 = ok
  329. $err_num = substr($line, 0, strpos($line, " "));
  330. switch ($err_num) {
  331. case 500: $message = "Syntax error; command not recognized";
  332. $status = 0;
  333. break;
  334. case 501: $message = "Syntax error in parameters or arguments";
  335. $status = 0;
  336. break;
  337. case 502: $message = "Command not implemented";
  338. $status = 0;
  339. break;
  340. case 503: $message = "Bad sequence of commands";
  341. $status = 0;
  342. break;
  343. case 504: $message = "Command parameter not implemented";
  344. $status = 0;
  345. break;
  346. case 211: $message = "System status, or system help reply";
  347. $status = 5;
  348. break;
  349. case 214: $message = "Help message";
  350. $status = 5;
  351. break;
  352. case 220: $message = "Service ready";
  353. $status = 5;
  354. break;
  355. case 221: $message = "Service closing transmission channel";
  356. $status = 5;
  357. break;
  358. case 421: $message = "Service not available, closing chanel";
  359. $status = 0;
  360. break;
  361. case 250: $message = "Requested mail action okay, completed";
  362. $status = 5;
  363. break;
  364. case 251: $message = "User not local; will forward";
  365. $status = 5;
  366. break;
  367. case 450: $message = "Requested mail action not taken: mailbox unavailable";
  368. $status = 0;
  369. break;
  370. case 550: $message = "Requested action not taken: mailbox unavailable";
  371. $status = 0;
  372. break;
  373. case 451: $message = "Requested action aborted: error in processing";
  374. $status = 0;
  375. break;
  376. case 551: $message = "User not local; please try forwarding";
  377. $status = 0;
  378. break;
  379. case 452: $message = "Requested action not taken: insufficient system storage";
  380. $status = 0;
  381. break;
  382. case 552: $message = "Requested mail action aborted: exceeding storage allocation";
  383. $status = 0;
  384. break;
  385. case 553: $message = "Requested action not taken: mailbox name not allowed";
  386. $status = 0;
  387. break;
  388. case 354: $message = "Start mail input; end with .";
  389. $status = 5;
  390. break;
  391. case 554: $message = "Transaction failed";
  392. $status = 0;
  393. break;
  394. default: $message = "Unknown response: ". nl2br(htmlspecialchars($lines));
  395. $status = 0;
  396. $error_num = "001";
  397. break;
  398. }
  399. if ($status == 0) {
  400. displayPageHeader($color, "None");
  401. echo "<TT>";
  402. echo "<br><b><font color=\"$color[1]\">ERROR</font></b><br><br>";
  403. echo "&nbsp;&nbsp;&nbsp;<B>Error Number: </B>$err_num<BR>";
  404. echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Reason: </B>$message<BR>";
  405. $lines = nl2br(htmlspecialchars($lines));
  406. echo "<B>Server Response: </B>$lines<BR>";
  407. echo "<BR>MAIL NOT SENT";
  408. echo "</TT></BODY></HTML>";
  409. exit;
  410. }
  411. return $err_num;
  412. }
  413. function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
  414. global $useSendmail, $msg_id, $is_reply, $mailbox;
  415. global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
  416. $more_headers = Array();
  417. $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
  418. if ($reply_id) {
  419. sqimap_mailbox_select ($imap_stream, $mailbox);
  420. sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, "Answered");
  421. // Insert In-Reply-To and References headers if the
  422. // message-id of the message we reply to is set (longer than "<>")
  423. // The References header should really be the old Referenced header
  424. // with the message ID appended, but it can be only the message ID too.
  425. $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
  426. if(strlen($hdr->message_id) > 2) {
  427. $more_headers["In-Reply-To"] = $hdr->message_id;
  428. $more_headers["References"] = $hdr->message_id;
  429. }
  430. sqimap_mailbox_close($imap_stream);
  431. }
  432. if ($useSendmail==true) {
  433. $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
  434. } else {
  435. $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
  436. }
  437. if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
  438. sqimap_append ($imap_stream, $sent_folder, $length);
  439. write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
  440. writeBody ($imap_stream, $body);
  441. sqimap_append_done ($imap_stream);
  442. }
  443. sqimap_logout($imap_stream);
  444. // Delete the files uploaded for attaching (if any).
  445. deleteAttachments();
  446. }
  447. ?>