smtp.php 18 KB

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