smtp.php 18 KB

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