smtp.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. // open pipe to sendmail
  206. $fp = popen (escapeshellcmd("$sendmail_path -t -f$username@$domain"), "w");
  207. $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
  208. $bodylength = writeBody($fp, $body);
  209. pclose($fp);
  210. return ($headerlength + $bodylength);
  211. }
  212. function smtpReadData($smtpConnection) {
  213. $read = fgets($smtpConnection, 1024);
  214. $counter = 0;
  215. while ($read) {
  216. echo $read . "<BR>";
  217. $data[$counter] = $read;
  218. $read = fgets($smtpConnection, 1024);
  219. $counter++;
  220. }
  221. }
  222. function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
  223. global $username, $domain, $version, $smtpServerAddress, $smtpPort,
  224. $data_dir, $color;
  225. $to = parseAddrs($t);
  226. $cc = parseAddrs($c);
  227. $bcc = parseAddrs($b);
  228. $from_addr = getPref($data_dir, $username, "email_address");
  229. if ($from_addr == "")
  230. $from_addr = "$username@$domain";
  231. $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
  232. if (!$smtpConnection) {
  233. echo "Error connecting to SMTP Server.<br>";
  234. echo "$errorNumber : $errorString<br>";
  235. exit;
  236. }
  237. $tmp = fgets($smtpConnection, 1024);
  238. errorCheck($tmp, $smtpConnection);
  239. $to_list = getLineOfAddrs($to);
  240. $cc_list = getLineOfAddrs($cc);
  241. /** Lets introduce ourselves */
  242. fputs($smtpConnection, "HELO $domain\r\n");
  243. $tmp = fgets($smtpConnection, 1024);
  244. errorCheck($tmp, $smtpConnection);
  245. /** Ok, who is sending the message? */
  246. fputs($smtpConnection, "MAIL FROM:<$from_addr>\r\n");
  247. $tmp = fgets($smtpConnection, 1024);
  248. errorCheck($tmp, $smtpConnection);
  249. /** send who the recipients are */
  250. for ($i = 0; $i < count($to); $i++) {
  251. fputs($smtpConnection, "RCPT TO:<$to[$i]>\r\n");
  252. $tmp = fgets($smtpConnection, 1024);
  253. errorCheck($tmp, $smtpConnection);
  254. }
  255. for ($i = 0; $i < count($cc); $i++) {
  256. fputs($smtpConnection, "RCPT TO:<$cc[$i]>\r\n");
  257. $tmp = fgets($smtpConnection, 1024);
  258. errorCheck($tmp, $smtpConnection);
  259. }
  260. for ($i = 0; $i < count($bcc); $i++) {
  261. fputs($smtpConnection, "RCPT TO:<$bcc[$i]>\r\n");
  262. $tmp = fgets($smtpConnection, 1024);
  263. errorCheck($tmp, $smtpConnection);
  264. }
  265. /** Lets start sending the actual message */
  266. fputs($smtpConnection, "DATA\r\n");
  267. $tmp = fgets($smtpConnection, 1024);
  268. errorCheck($tmp, $smtpConnection);
  269. // Send the message
  270. $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
  271. $bodylength = writeBody($smtpConnection, $body);
  272. fputs($smtpConnection, ".\r\n"); // end the DATA part
  273. $tmp = fgets($smtpConnection, 1024);
  274. $num = errorCheck($tmp, $smtpConnection);
  275. if ($num != 250) {
  276. $tmp = nl2br(htmlspecialchars($tmp));
  277. echo "ERROR<BR>Message not sent!<BR>Reason given: $tmp<BR></BODY></HTML>";
  278. }
  279. fputs($smtpConnection, "QUIT\r\n"); // log off
  280. fclose($smtpConnection);
  281. return ($headerlength + $bodylength);
  282. }
  283. function errorCheck($line, $smtpConnection) {
  284. global $page_header_php;
  285. global $color;
  286. if (!isset($page_header_php)) {
  287. include "../functions/page_header.php";
  288. }
  289. // Read new lines on a multiline response
  290. $lines = $line;
  291. while(ereg("^[0-9]+-", $line)) {
  292. $line = fgets($smtpConnection, 1024);
  293. $lines .= $line;
  294. }
  295. // Status: 0 = fatal
  296. // 5 = ok
  297. $err_num = substr($line, 0, strpos($line, " "));
  298. switch ($err_num) {
  299. case 500: $message = "Syntax error; command not recognized";
  300. $status = 0;
  301. break;
  302. case 501: $message = "Syntax error in parameters or arguments";
  303. $status = 0;
  304. break;
  305. case 502: $message = "Command not implemented";
  306. $status = 0;
  307. break;
  308. case 503: $message = "Bad sequence of commands";
  309. $status = 0;
  310. break;
  311. case 504: $message = "Command parameter not implemented";
  312. $status = 0;
  313. break;
  314. case 211: $message = "System status, or system help reply";
  315. $status = 5;
  316. break;
  317. case 214: $message = "Help message";
  318. $status = 5;
  319. break;
  320. case 220: $message = "Service ready";
  321. $status = 5;
  322. break;
  323. case 221: $message = "Service closing transmission channel";
  324. $status = 5;
  325. break;
  326. case 421: $message = "Service not available, closing chanel";
  327. $status = 0;
  328. break;
  329. case 250: $message = "Requested mail action okay, completed";
  330. $status = 5;
  331. break;
  332. case 251: $message = "User not local; will forward";
  333. $status = 5;
  334. break;
  335. case 450: $message = "Requested mail action not taken: mailbox unavailable";
  336. $status = 0;
  337. break;
  338. case 550: $message = "Requested action not taken: mailbox unavailable";
  339. $status = 0;
  340. break;
  341. case 451: $message = "Requested action aborted: error in processing";
  342. $status = 0;
  343. break;
  344. case 551: $message = "User not local; please try forwarding";
  345. $status = 0;
  346. break;
  347. case 452: $message = "Requested action not taken: insufficient system storage";
  348. $status = 0;
  349. break;
  350. case 552: $message = "Requested mail action aborted: exceeding storage allocation";
  351. $status = 0;
  352. break;
  353. case 553: $message = "Requested action not taken: mailbox name not allowed";
  354. $status = 0;
  355. break;
  356. case 354: $message = "Start mail input; end with .";
  357. $status = 5;
  358. break;
  359. case 554: $message = "Transaction failed";
  360. $status = 0;
  361. break;
  362. default: $message = "Unknown response: ". nl2br(htmlspecialchars($lines));
  363. $status = 0;
  364. $error_num = "001";
  365. break;
  366. }
  367. if ($status == 0) {
  368. displayPageHeader($color, "None");
  369. echo "<TT>";
  370. echo "<br><b><font color=\"$color[1]\">ERROR</font></b><br><br>";
  371. echo "&nbsp;&nbsp;&nbsp;<B>Error Number: </B>$err_num<BR>";
  372. echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Reason: </B>$message<BR>";
  373. $lines = nl2br(htmlspecialchars($lines));
  374. echo "<B>Server Response: </B>$lines<BR>";
  375. echo "<BR>MAIL NOT SENT";
  376. echo "</TT></BODY></HTML>";
  377. exit;
  378. }
  379. return $err_num;
  380. }
  381. function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
  382. global $useSendmail, $msg_id, $is_reply, $mailbox;
  383. global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
  384. $more_headers = Array();
  385. $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
  386. if ($reply_id) {
  387. sqimap_mailbox_select ($imap_stream, $mailbox);
  388. sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, "Answered");
  389. // Insert In-Reply-To and References headers if the
  390. // message-id of the message we reply to is set (longer than "<>")
  391. // The References header should really be the old Referenced header
  392. // with the message ID appended, but it can be only the message ID too.
  393. $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
  394. if(strlen($hdr->message_id) > 2) {
  395. $more_headers["In-Reply-To"] = $hdr->message_id;
  396. $more_headers["References"] = $hdr->message_id;
  397. }
  398. sqimap_mailbox_close($imap_stream);
  399. }
  400. if ($useSendmail==true) {
  401. $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
  402. } else {
  403. $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
  404. }
  405. if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
  406. sqimap_append ($imap_stream, $sent_folder, $length);
  407. write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
  408. writeBody ($imap_stream, $body);
  409. sqimap_append_done ($imap_stream);
  410. }
  411. sqimap_logout($imap_stream);
  412. // Delete the files uploaded for attaching (if any).
  413. deleteAttachments();
  414. }
  415. ?>