欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

PHP处理postfix的邮件内容

程序员文章站 2022-06-14 22:50:20
...
  1. 01
  2. 02
  3. 03 #从输入读取到所有的邮件内容
  4. 04 $email = "";
  5. 05 $fd = fopen("php://stdin", "r");
  6. 06 while (!feof($fd)) {
  7. 07 $email .= fread($fd, 1024);
  8. 08 }
  9. 09 fclose($fd);
  10. 10
  11. 11 #记录所有的内容,测试
  12. 12 file_put_contents("/tmp/mail/".time(), $email);
  13. 13
  14. 14 #处理邮件
  15. 15 $lines = explode("\n", $email);
  16. 16
  17. 17 // empty vars
  18. 18 $from = "";
  19. 19 $date = "";
  20. 20 $subject = "";
  21. 21 $message = "";
  22. 22 $splittingheaders = true;
  23. 23
  24. 24 for ($i=0; $icount($lines); $i++) {
  25. 25 if ($splittingheaders) {
  26. 26
  27. 27 // look out for special headers
  28. 28 if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
  29. 29 $subject = $matches[1];
  30. 30 }
  31. 31 if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
  32. 32 if(strpos($lines[$i],")){
  33. 33 //the name exist too in from header
  34. 34 $data = explode(',$lines[$i]);
  35. 35 $from = substr(trim($data[1]),0,-1);
  36. 36 }else{
  37. 37 //only the mail
  38. 38 $from = $matches[1];
  39. 39 }
  40. 40 }
  41. 41 if (preg_match("/^Date: (.*)/", $lines[$i], $matches)) {
  42. 42 $date = $matches[1];
  43. 43 }
  44. 44 } else {
  45. 45 // not a header, but message
  46. 46 $message .= $lines[$i]."\n";
  47. 47 }
  48. 48
  49. 49 if (trim($lines[$i])=="") {
  50. 50 // empty line, header section has ended
  51. 51 $splittingheaders = false;
  52. 52 }
  53. 53 }
  54. 54
  55. 55 $when = date("Y-m-d G:i:s");
  56. 56 $data = explode('@',$from);
  57. 57 $username = $data[0];
  58. 58
  59. 59 #记录到数据库
  60. 60 $sql = "insert into mails ( `username`, `from`, `subject`, `date`, `message`) values ( '$username', '$from', '$subject', '$when', '$message')";
  61. 61
  62. 62 #测试
  63. 63 file_put_contents("/tmp/mail2.log", $sql);
  64. 64 ?>