PHP Receive mail Receivemail

Source: Internet
Author: User
Tags explode 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 reads the inbox primarily with IMAP extensions, so you must turn on IMAP extension support 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:

<?php//Main recivemail Class file-version 1.0 (03-06-2015)/* * File:recivemail.class.php * description:reciving ma Il with attechment * version:1.1 * created:03-06-2015 * Author:sara Zhou */class receivemail{var $server = '; var $userna Me= '; var $password = '; var $marubox = '; var $email = '; function receivemail ($username, $password, $EmailAddress, $ mailserver= ' localhost ', $servertype = ' Pop ', $port = ' + ', $ssl = False)//constructure{if ($servertype = = ' IMAP ') {if ($ port== ") $port = ' 143 '; $strConnect = ' {'. $mailserver. ': '. $port. '}inbox '; }else{$strConnect = ' {'. $mailserver. ': ' $port. '/pop3 '. ($ssl? "/ssl": ""). '} INBOX '; } $this->server= $strConnect, $this->username= $username, $this->password= $password; $this->email=$ EmailAddress;} function connect ()//connect to the Mail box{$this->[email protected]_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 Inte Rnal Private use{if (! $structure) {$structure = Imap_fetchstructure ($stream, $msg _number);} if ($structure) {if ($mime _ty PE = = $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 ima P_headers ($this->marubox); 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;//Take the message attachment if ($str uckture->parts[$key]->ifdparameters) {//name attachments, 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 '] =!empty ($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); if (!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, ' 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;}}? >

3. Control layer./mailreceived/mailcontrol.php

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

<?/* * File:mailControl.php * description:received Mail Example * created:03-06-2015 * Author:sara Zhou * * @header (' Content-type:text/html;charset=utf-8 '); error_reporting (0); Ignore_user_abort (); Run script in Backgroundset_time_limit (0); Run script foreverdate_default_timezone_set (' Asia/shanghai '); include ("receivemail.class.php"); class Mailcontrol {//define system constants//user name public $mailAccount = "[email protected]";p ublic $mailPasswd = "12345";p ublic $mailAddress = "[Email  protected] ";p ublic $mailServer =" pop.qq.com ";p ublic $serverType =" POP3 ";p ublic $port =" a ";p ublic $now = 0 ;p ublic $savePath = ";p ublic $webPath =". /upload/";p ublic function __construct () {$this->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-&gT;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 <br>"), 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 "<pre>";p Rint_r ($res);//Create Mailbox//$obj->creatbox ("Readybox"); >

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



PHP Receive mail Receivemail

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.