ReceiveMail.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. <?php
  2. // Main ReciveMail Class File - Version 1.0 (03-06-2015)
  3. /*
  4. * File: recivemail.class.php
  5. * Description: Reciving mail With Attechment
  6. * Version: 1.1
  7. * Created: 03-06-2015
  8. * Author: Sara Zhou
  9. */
  10. namespace addons\qingdongams\library;
  11. class ReceiveMail
  12. {
  13. var $server='';
  14. var $username='';
  15. var $password='';
  16. var $marubox='';
  17. var $email='';
  18. function __construct($username,$password,$EmailAddress,$mailserver='localhost',$servertype='pop',$port='110',$ssl = false) //Constructure
  19. {
  20. if($servertype=='imap')
  21. {
  22. if($port=='') $port='143';
  23. $strConnect='{'.$mailserver.':'.$port. '}INBOX';
  24. }
  25. else
  26. {
  27. $strConnect='{'.$mailserver.':'.$port. '/pop3'.($ssl ? "/ssl" : "").'}INBOX';
  28. // $strConnect="{pop.163.com:110/pop3}INBOX";
  29. }
  30. $this->server = $strConnect;
  31. $this->username = $username;
  32. $this->password = $password;
  33. $this->email = $EmailAddress;
  34. }
  35. function connect() //Connect To the Mail Box
  36. {
  37. ini_set("display_errors", "On");//打开错误提示
  38. ini_set("error_reporting",E_ALL);//显示所有错误
  39. $this->marubox=@imap_open($this->server,$this->username,$this->password);
  40. if(!$this->marubox)
  41. {
  42. return false;
  43. // echo "Error: Connecting to mail server";
  44. // exit;
  45. }
  46. return true;
  47. }
  48. function getHeaders($mid) // Get Header info
  49. {
  50. if(!$this->marubox)
  51. return false;
  52. $mail_header=imap_header($this->marubox,$mid);
  53. $sender=$mail_header->from[0];
  54. $sender_replyto=$mail_header->reply_to[0];
  55. // if(strtolower($sender->mailbox)!='mailer-daemon' && strtolower($sender->mailbox)!='postmaster') // 退信的发件人是postmaster哦
  56. $subject=$this->decode_mime($mail_header->subject);
  57. $ccList=array();
  58. if(isset($mail_header->cc)){
  59. foreach ($mail_header->cc as $k => $v)
  60. {
  61. $ccList[]=$v->mailbox.'@'.$v->host;
  62. }
  63. }
  64. $toList=array();
  65. if(isset($mail_header->to)){
  66. foreach ($mail_header->to as $k => $v)
  67. {
  68. $toList[]=$v->mailbox.'@'.$v->host;
  69. }
  70. }
  71. $ccList=implode(",", $ccList);
  72. $toList=implode(",", $toList);
  73. $mail_details=array(
  74. 'fromBy'=>strtolower($sender->mailbox).'@'.$sender->host,
  75. 'fromName'=>isset($sender->personal) ? $this->decode_mime($sender->personal) : $sender->mailbox,
  76. 'ccList'=>$ccList,//strtolower($sender_replyto->mailbox).'@'.$sender_replyto->host,
  77. 'toNameOth'=>isset($sender_replyto->personal) ? $this->decode_mime($sender_replyto->personal) : $sender_replyto->mailbox, //转换邮件标题的字符编码,处理乱码(猜测应该是如果要回复邮箱,回复人)
  78. 'subject'=>$subject,
  79. 'mailDate'=>date("Y-m-d H:i:s",$mail_header->udate),
  80. 'udate'=>$mail_header->udate,
  81. 'toList'=>$toList//strtolower($mail_header->to[0]->mailbox).'@'.$mail_header->to[0]->host
  82. // 'to'=>strtolower($mail_header->toaddress)
  83. );
  84. return $mail_details;
  85. }
  86. function get_mime_type(&$structure) //Get Mime type Internal Private Use
  87. {
  88. $primary_mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
  89. if($structure->subtype && $structure->subtype!="PNG") {
  90. return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype;
  91. }
  92. return "TEXT/PLAIN";
  93. }
  94. function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) //Get Part Of Message Internal Private Use
  95. {
  96. if(!$structure) {
  97. $structure = imap_fetchstructure($stream, $msg_number);
  98. }
  99. if($structure) {
  100. if($mime_type == $this->get_mime_type($structure))
  101. {
  102. if(!$part_number)
  103. {
  104. $part_number = "1";
  105. }
  106. $text = imap_fetchbody($stream, $msg_number, $part_number);
  107. if($structure->encoding == 3)
  108. {
  109. if ($structure->parameters[0]->value!="utf-8")
  110. {
  111. return iconv('GB2312','UTF-8//IGNORE',imap_base64($text));
  112. }
  113. else
  114. {
  115. return iconv('GB2312','UTF-8//IGNORE',imap_base64($text));
  116. }
  117. }
  118. else if($structure->encoding == 4)
  119. {
  120. if ($structure->parameters[0]->value =="utf-8" || $structure->parameters[0]->value =='UTF-8')
  121. {
  122. return imap_qprint($text);
  123. }
  124. else
  125. {
  126. echo iconv('GB2312','UTF-8//IGNORE',imap_base64($text));
  127. }
  128. }
  129. else
  130. {
  131. return iconv('GB2312','UTF-8//IGNORE',$text);
  132. }
  133. }
  134. if($structure->type == 1) /* multipart */
  135. {
  136. while(list($index, $sub_structure) = $this->fun_adm_each($structure->parts))
  137. {
  138. $prefix = '';
  139. if($part_number)
  140. {
  141. $prefix = $part_number . '.';
  142. }
  143. $data = $this->get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1));
  144. if($data)
  145. {
  146. return $data;
  147. }
  148. }
  149. }
  150. }
  151. return false;
  152. }
  153. function fun_adm_each(&$array)
  154. {
  155. $res = array();
  156. $key = key($array);
  157. if ($key !== null) {
  158. next($array);
  159. $res[1] = $res['value'] = $array[$key];
  160. $res[0] = $res['key'] = $key;
  161. } else {
  162. $res = false;
  163. }
  164. return $res;
  165. }
  166. function getTotalMails() //Get Total Number off Unread Email In Mailbox
  167. {
  168. if(!$this->marubox)
  169. return false;
  170. // return imap_headers($this->marubox);
  171. return imap_num_recent($this->marubox);
  172. }
  173. function GetAttach($mid,$path) // Get Atteced File from Mail
  174. {
  175. if(!$this->marubox)
  176. return false;
  177. $struckture = imap_fetchstructure($this->marubox,$mid); // 获取某信件的结构信息
  178. $files=array();
  179. if(isset($struckture->parts))
  180. {
  181. foreach($struckture->parts as $key => $value)
  182. {
  183. $enc=$struckture->parts[$key]->encoding;
  184. //取邮件附件
  185. if($struckture->parts[$key]->ifdparameters)
  186. {
  187. //命名附件,转码
  188. $name=$this->decode_mime($struckture->parts[$key]->dparameters[0]->value);
  189. $extend =explode("." , $name);
  190. $file['extension'] = $extend[count($extend)-1];
  191. $file['pathname'] = $this->setPathName($key, $file['extension']);
  192. $file['title'] = !empty($name) ? htmlspecialchars($name) : str_replace('.' . $file['extension'], '', $name);
  193. $file['size'] = isset($struckture->parts[$key]->dparameters) ? $struckture->parts[$key]->dparameters[0]->value : 0;
  194. $file['tmpname'] = $struckture->parts[$key]->dparameters[0]->value;
  195. if(@$struckture->parts[$key]->disposition=="ATTACHMENT")
  196. {
  197. $file['type'] = 1;
  198. }
  199. else
  200. {
  201. $file['type'] = 0;
  202. }
  203. $files[] = $file;
  204. $message = imap_fetchbody($this->marubox,$mid,$key+1);
  205. if ($enc == 0)
  206. $message = imap_8bit($message);
  207. if ($enc == 1)
  208. $message = imap_8bit ($message);
  209. if ($enc == 2)
  210. $message = imap_binary ($message);
  211. if ($enc == 3)//图片
  212. $message = imap_base64 ($message);
  213. if ($enc == 4)
  214. $message = quoted_printable_decode($message);
  215. if ($enc == 5)
  216. $message = $message;
  217. $fp=fopen($path.$file['pathname'],"w");
  218. fwrite($fp,$message);
  219. fclose($fp);
  220. }
  221. // 处理内容中包含图片的部分
  222. if(isset($struckture->parts) && isset($struckture->parts[$key]->parts)){
  223. if($struckture->parts[$key]->parts)
  224. {
  225. foreach($struckture->parts[$key]->parts as $keyb => $valueb)
  226. {
  227. $enc=$struckture->parts[$key]->parts[$keyb]->encoding;
  228. if($struckture->parts[$key]->parts[$keyb]->ifdparameters)
  229. {
  230. //命名图片
  231. $name=$this->decode_mime($struckture->parts[$key]->parts[$keyb]->dparameters[0]->value);
  232. $extend =explode("." , $name);
  233. $file['extension'] = $extend[count($extend)-1];
  234. $file['pathname'] = $this->setPathName($key, $file['extension']);
  235. $file['title'] = !empty($name) ? htmlspecialchars($name) : str_replace('.' . $file['extension'], '', $name);
  236. $file['size'] = $struckture->parts[$key]->parts[$keyb]->dparameters[0]->value;
  237. // $file['tmpname'] = $struckture->parts[$key]->dparameters[0]->value;
  238. $file['type'] = 0;
  239. $files[] = $file;
  240. $partnro = ($key+1).".".($keyb+1);
  241. $message = imap_fetchbody($this->marubox,$mid,$partnro);
  242. if ($enc == 0)
  243. $message = imap_8bit($message);
  244. if ($enc == 1)
  245. $message = imap_8bit ($message);
  246. if ($enc == 2)
  247. $message = imap_binary ($message);
  248. if ($enc == 3)
  249. $message = imap_base64 ($message);
  250. if ($enc == 4)
  251. $message = quoted_printable_decode($message);
  252. if ($enc == 5)
  253. $message = $message;
  254. $fp=fopen($path.$file['pathname'],"w");
  255. fwrite($fp,$message);
  256. fclose($fp);
  257. }
  258. }
  259. }
  260. }
  261. }
  262. }
  263. //move mail to taskMailBox
  264. $this->move_mails($mid, $this->marubox);
  265. return $files;
  266. }
  267. function getBody($mid,&$path,$imageList) // Get Message Body
  268. {
  269. if(!$this->marubox)
  270. return false;
  271. $body = $this->get_part($this->marubox, $mid, "TEXT/HTML");
  272. if ($body == "")
  273. $body = $this->get_part($this->marubox, $mid, "TEXT/PLAIN");
  274. if ($body == "") {
  275. return "";
  276. }
  277. //处理图片
  278. $body=$this->embed_images($body,$path,$imageList);
  279. return $body;
  280. }
  281. function embed_images(&$body,&$path,$imageList)
  282. {
  283. // get all img tags
  284. preg_match_all('/<img.*?>/', $body, $matches);
  285. if (!isset($matches[0])) return;
  286. foreach ($matches[0] as $img)
  287. {
  288. // replace image web path with local path
  289. preg_match('/src="(.*?)"/', $img, $m);
  290. if (!isset($m[1])) continue;
  291. $arr = parse_url($m[1]);
  292. if (!isset($arr['scheme']) || !isset($arr['path']))continue;
  293. // if (!isset($arr['host']) || !isset($arr['path']))continue;
  294. if ($arr['scheme']!="http")
  295. {
  296. $filename=explode("@", $arr['path']);
  297. if($imageList){
  298. $body = str_replace($img, '<img alt="" src="'.$path.$imageList[$filename[0]].'" style="border: none;" />', $body);
  299. }
  300. }
  301. }
  302. return $body;
  303. }
  304. function deleteMails($mid) // Delete That Mail
  305. {
  306. if(!$this->marubox)
  307. return false;
  308. imap_delete($this->marubox,$mid);
  309. }
  310. function close_mailbox() //Close Mail Box
  311. {
  312. if(!$this->marubox)
  313. return false;
  314. imap_close($this->marubox,CL_EXPUNGE);
  315. }
  316. //移动邮件到指定分组
  317. function move_mails($msglist,$mailbox)
  318. {
  319. if(!$this->marubox)
  320. return false;
  321. imap_mail_move($this->marubox, $msglist, json_encode($mailbox));
  322. }
  323. function creat_mailbox($mailbox)
  324. {
  325. if(!$this->marubox)
  326. return false;
  327. //imap_renamemailbox($imap_stream, $old_mbox, $new_mbox);
  328. imap_create($this->marubox, $mailbox);
  329. }
  330. /*
  331. * decode_mime()转换邮件标题的字符编码,处理乱码
  332. */
  333. function decode_mime($str){
  334. $str=imap_mime_header_decode($str);
  335. if ($str[0]->charset!="default")
  336. {
  337. return iconv($str[0]->charset,'utf8',$str[0]->text);
  338. }
  339. else
  340. {
  341. return $str[0]->text;
  342. }
  343. }
  344. /**
  345. * Set path name of the uploaded file to be saved.
  346. *
  347. * @param int $fileID
  348. * @param string $extension
  349. * @access public
  350. * @return string
  351. */
  352. public function setPathName($fileID, $extension)
  353. {
  354. $destDir = 'public/emails/'.date('ymd');
  355. $absoluteDir = ROOT_PATH . $destDir;
  356. if (!is_dir($absoluteDir)) {
  357. @mkdir($absoluteDir, 0755, true);
  358. }
  359. return $destDir.'/'.date('ymd', time()) . $fileID . mt_rand(0, 10000) . '.' . $extension;
  360. // return date('Ym/dHis', time()) . $fileID . mt_rand(0, 10000) . '.' . $extension;
  361. // return 'public/emails/'.date('ymd', time()) . $fileID . mt_rand(0, 10000) . '.' . $extension;
  362. }
  363. }
  364. ?>