PHP Receive mail Receivemail

Source: Internet
Author: User
Tags imap mail example
With PHP to send e-mail, I believe we are not unfamiliar, but read Inbox, contact is less, this summary of their own experience, hope can help everyone.

Note: 1.PHP read Inbox is primarily an IMAP extension, so you must turn on support for IMAP extensions before using the following methods.

2. This method supports Chinese, does not garbled, need to maintain the encoding consistency of all files

1. File structure


2. Mail class./mailreceived/receivemail.class.php

The./mailreceived/receivemail.class.php file reads as follows:

 Server= $strConnect, $this->username= $username, $this->password= $password; $this->email= $EmailAddress;} function connect ()//connect to the Mail box{$this->marubox= @imap_open ($this->server, $this->username, $this- >password), if (! $this->marubox) {return false;//echo "error:connecting to mail Server";//Exit;} return true;} function Getheaders ($mid)//Get Header info{if (! $this->marubox) return false; $mail _header=imap_header ($this Marubox, $mid); $sender = $mail _header->from[0]; $sender _replyto= $mail _header->reply_to[0];if (Strtolower ($ Sender->mailbox)! = ' Mailer-daemon ' && strtolower ($sender->mailbox)! = ' postmaster ') {$subject = $this- >decode_mime ($mail _header->subject), $ccList =array (), foreach ($mail _header->cc as $k = $v) {$ccList []=$ V->mailbox. ' @ '. $v->host;} $toList =array (), foreach ($mail _header->to as $k = + $v) {$toList []= $v->mailbox. ' @ '. $v->host;} $ccList =implode (",", $ccList), $toList =implode (",", $toList); $mail _details=array ('Fromby ' =>strtolower ($sender->mailbox). ' @ '. $sender->host, ' fromname ' = $this->decode_mime ($sender->personal), ' cclist ' = $ccList,// Strtolower ($sender _replyto->mailbox). ' @ '. $sender _replyto->host, ' tonameoth ' = $this->decode_mime ($sender _replyto->personal), ' subject ' = $subject, ' maildate ' =>date ("y-m-d h:i:s", $mail _header->udate), ' udate ' = $mail _header->udate, ' toList ' = > $toList//strtolower ($mail _header->to[0]->mailbox). ' @ '. $mail _header->to[0]->host//' to ' =>strtolower ($mail _header->toaddress);} return $mail _details;} Function Get_mime_type (& $structure)//get MIME type Internal Private use{$primary _mime_type = Array ("TEXT", "Multipa RT "," MESSAGE "," Application "," AUDIO "," IMAGE "," VIDEO "," other "); if ($structure->subtype && $structure->subtype!= "PNG") {return $primary _mime_type[(int) $structure- >type]. '/' . $structure->subtype; } return "Text/plain"; } function Get_part ($stream, $msg _number, $mime _type,$structure = False, $part _number = False)//get part of Message Internal Private use{if (! $structure) {$structure = Imap_ Fetchstructure ($stream, $msg _number); if ($structure) {if ($mime _type = = $this->get_mime_type ($structure)) {if (! $part _number) {$part _number = "1";} $text = Imap_fetchbody ($stream, $msg _number, $part _number), if ($structure->encoding = = 3) {return imap_base64 ($text);/If ($structure->parameters[0]->value!= "utf-8")//{//Return imap_base64 ($text);//}//else//{//return imap_base64 ($text);//}}else if ($structure->encoding = = 4) {return iconv (' gb2312 ', ' UTF8 ', Imap_qprint ($text));} Else{return iconv (' gb2312 ', ' UTF8 ', $text);}} if ($structure->type = = 1)/* multipart * * (List ($index, $sub _structure) = each ($structure->parts)) {if ($part _number) {$prefix = $part _number. '.'; } $data = $this->get_part ($stream, $msg _number, $mime _type, $sub _structure, $prefix. ($index + 1)); if ($data) {return $data;}} }}return false; } function Gettotalmails () Get Total number off unread e-mail in mailbox{if (! $this->marubox) return false;//return imap_headers ($this->marub OX); return imap_num_recent ($this->marubox);} function Getattach ($mid, $path)//Get atteced File from mail{if (! $this->marubox) return false; $struckture = Imap_ Fetchstructure ($this->marubox, $mid); $files =array (); if ($struckture->parts) {foreach ($struckture->parts As $key + $value) {$enc = $struckture->parts[$key]->encoding;//to pick up the mail attachment if ($struckture->parts[$key]-> Ifdparameters) {//name attachment, transcoding $name= $this->decode_mime ($struckture->parts[$key]->dparameters[0]->value); $extend =explode (".", $name); $file [' extension '] = $extend [Count ($extend)-1]; $file [' pathname '] = $this Setpathname ($key, $file [' extension ']); $file [' title '] =!empty ($name)? Htmlspecialchars ($name): Str_replace ('. '. $file [' extension '], ', $name); $file [' size '] = $struckture->parts[$key ]->dparameters[1]->value;//$file [' tmpname '] = $struckture->parts[$key]->dparameters[0]->value;if (@ $struckture->parts[$key]->disposition== "ATTACHMENT") {$file [' Type '] = 1;} else{$file [' type '] = 0;} $files [] = $file; $message = Imap_fetchbody ($this->marubox, $mid, $key + 1), if ($enc = = 0) $message = imap_8bit ($message);  if ($enc = = 1) $message = Imap_8bit ($message), if ($enc = = 2) $message = Imap_binary ($message), if ($enc = = 3)//Picture $message = Imap_base64 ($message); if ($enc = = 4) $message = Quoted_printable_decode ($message), if ($enc = = 5) $message = $message, $fp =fopen ($path. $file [' Pathname '], "w"); Fwrite ($fp, $message); fclose ($FP);} Process the part of the content that contains the picture if ($struckture->parts[$key]->parts) {foreach ($struckture->parts[$key]->parts as $keyb = > $valueb) {$enc = $struckture->parts[$key]->parts[$keyb]->encoding;if ($struckture->parts[$key] >parts[$keyb]->ifdparameters) {//Name picture $name= $this->decode_mime ($struckture->parts[$key]->parts[$ Keyb]->dparameters[0]->value); $extend =explode (".", $name); $file [' extension '] = $extend [Count ($extend)-1]; $file [' pathname '] = $this->setpathname ($key, $file [' extension ']); $file [' title '] =!em Pty ($name)? Htmlspecialchars ($name): Str_replace ('. '. $file [' extension '], ', $name); $file [' size '] = $struckture->parts[$key ]->parts[$keyb]->dparameters[1]->value;//$file [' tmpname '] = $struckture->parts[$key]->dparameters [0]->value; $file [' type '] = 0; $files [] = $file; $partnro = ($key + 1). ".". ($keyb + 1); $message = Imap_fetchbody ($this->marubox, $mid, $partnro), if ($enc = = 0) $message = imap_8bit ($message); $enc = = 1) $message = Imap_8bit ($message), if ($enc = = 2) $message = Imap_binary ($message), if ($enc = = 3) $message = Imap_base64 ($message), if ($enc = = 4) $message = Quoted_printable_decode ($message), if ($enc = = 5) $message = $messag e; $fp =fopen ($path. $file [' pathname '], ' W '), Fwrite ($fp, $message); fclose ($FP);}}}} Move mail to Taskmailbox$this->move_mails ($mid, $this->marubox); return $files;} function GetBody ($mid,& $path, $imageList)//Get Message body{if (! $this->marubox) return false; $body = $this->get_part ($this- >marubox, $mid, "text/html"), if ($body = = "") $body = $this->get_part ($this->marubox, $mid, "Text/plain"); if ($ BODY = = "") {return "";} Process picture $body= $this->embed_images ($body, $path, $imageList); return $body;} Function embed_images (& $body,& $path, $imageList) {//Get all img Tagspreg_match_all ('///', $body, $matches); Isset ($matches [0])) return;foreach ($matches [0] as $img) {//Replace Image Web path with local pathpreg_match ('/src= ' (. *?) "/", $img, $m), if (!isset ($m [1])) continue; $arr = Parse_url ($m [1]); if (!isset ($arr [' scheme ')] | |! Isset ($arr [' path ']) continue;//if (!isset ($arr [' Host ']) | |!isset ($arr [' path ']) continue;if ($arr [' scheme ']!= ' http {$filename =explode ("@", $arr [' Path ']), $body = Str_replace ($img, ', $body);}} return $body;} function Deletemails ($mid)//Delete that mail{if (! $this->marubox) return False;imap_delete ($this->marubox, $mid );} FunctIon Close_mailbox ()//close Mail box{if (! $this->marubox) return False;imap_close ($this->marubox,cl_expunge);} Move mail to the specified grouping function move_mails ($msglist, $mailbox) {if (! $this->marubox) return False;imap_mail_move ($this Marubox, $msglist, $mailbox);} function Creat_mailbox ($mailbox) {if (! $this->marubox) return False;//imap_renamemailbox ($imap _stream, $old _mbox, $new _mbox); Imap_create ($this->marubox, $mailbox);} /* * Decode_mime () converts the character encoding of the message header, handles garbled */function Decode_mime ($str) {$str =imap_mime_header_decode ($STR); return $str [0]- >text;echo "str";p Rint_r ($STR), if ($str [0]->charset!= "Default") {echo "= =". $str [0]->text;return iconv ($str [0]->charset, ' UTF8 ', $str [0]->text];} Else{return $str [0]->text;}} /** * Set path name of the uploaded file to is saved. * * @param int $fileID * @param string $extension * @access public * @return string */public function Setpathname ($fi LeID, $extension) {return date (' Ym/dhis ', Time ()). $fileID. Mt_rand (0, 10000). '.' . $extension;}}? &Gt 

3. Control layer./mailreceived/mailcontrol.php

The./mailreceived/mailcontrol.php content is as follows:

 now = Date ("Y-m-d h:i:s", Time ()), $this->setsavepath ();} /** * Mail Received () read Inbox mail * * @param * @access public * @return result */public function mailreceived () {//Creating a O Bject of Recivemail class$obj= new Receivemail ($this->mailaccount, $this->mailpasswd, $this->mailaddress,$ This->mailserver, $this->servertype, $this->port,false);         Connect to the Mail box$res= $obj->connect (); If connection fails give error message and EXITIF (! $res) {return Array ("MSG" = "error:connecting to mail Server");} Get total number of unread emails in mail box$tot= $obj->gettotalmails (); Total mails in Inbox return integer valueif ($tot < 1) {//If the number of letters is 0, display the message Return array ("MSG" and "No message for". $this- >mailaccount);} else{$res =array ("msg" = "total mails:: $tot
for ($i = $tot; $i >0; $i-) {$head = $obj->getheaders ($i); Get Header Info Return Array of Headers **array Keys is (subject,to,tooth,tonameoth,from,fromname)//processing mail attachments $files= $obj ->getattach ($i, $this->savepath); Gets the message attachment, returns the message attachment information array $imagelist=array (); foreach ($files as $k + $file) {//type=1 is an attachment, 0 is the message content picture if ($file [' type '] = = 0) { $imageList [$file [' title ']]= $file [' pathname '];}} $body = $obj->getbody ($i, $this->webpath, $imageList); $res [' Mail '][]=array (' head ' + $head, ' body ' + $body , "attachlist" = $files); $obj->deletemails ($i); Delete Mail from Mail box//$obj->move_mails ($i, "Taskmail");} $obj->close_mailbox (); Close Mail Boxreturn $res;}} /*** creatbox** @access public* @return void*/public function Creatbox ($boxName) {//Creating a object of Recivemail class$ obj= New Receivemail ($this->mailaccount, $this->mailpasswd, $this->mailaddress, $this->mailserver,$ This->servertype, $this->port,false); $obj->creat_mailbox ($boxName);} /** * SET save path. * * @access public * @return void */public function Setsavepath () {$savePath = ": /upload/". Date (' ym/', $this->now), if (!file_exists ($savePath)) {@mkdir ($savePath, 0777, true); Touch ($savePath. ' index.html ');} $this->savepath = dirname ($savePath). '/';} } $obj =new Mailcontrol (); Receive mail $res= $obj->mailreceived (); echo "
";p Rint_r ($res);//Create Mailbox//  $obj->creatbox (" Readybox "); >

4. Access Address: http://localhost/test.cn/mailreceived/mailControl.php

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.