Examples of IMAP applications in PHP (send and receive mail, delete messages, download attachments)

Source: Internet
Author: User
Tags imap gtar
This article introduces the use of IMAP in PHP to send and receive mail, delete messages and attachments download examples, the need for friends, refer to the next.

The complete code for the IMAP instance in PHP is as follows:

Copy Codecode example:

* @version $ $Id: email.php 175 2011-03-26 09:52:16z Chen.qiao $$ * @copyright Copyright (c) Jbxue Inc. (HTTP// bbs.it-home.org) */

/** * Email class * * Get mail total count,get mail list,get mail content,get mail Attach * * to a example, if you wan T to get some specified email list. * * $mail = new Jbxue_mail (); * $mail->mailconnect ($host, $port, $user, $pass, ' INBOX ', $SSL); * $mail->maillist (' 5,9:20 '); * * * Show the Five,and nine to twenty mail. * * $mail->maillist (' 5,9:20 '); * * * @docinfo * * @package application * @author Chen Qiao * @version $ $Id: email.php 175 2011-03-26 09:52:16z Chen.qiao $$ */class jbxue_email {/** * @var resource $ _connect */Private $_connect; /** * @var Object $_mailinfo */private $_mailinfo; /** * @var int $_totalcount */private $_totalcount; /** * @var Array $_totalcount */private $_contenttype;

/** * __construct of the class */Public Function __construct () {$this->_contenttype = array (' ez ' = = ' application/ Andrew-inset ', ' hqx ' = ' application/mac-binhex40 ', ' cpt ' = ' Application/mac-compactpro ', ' doc ' = ' Application/msword ', ' bin ' = ' application/octet-stream ', ' dms ' = ' application/octet-stream ', ' lha ' = ' Application/octet-stream ', ' lzh ' = ' application/octet-stream ', ' exe ' = ' application/octet-stream ', ' class ' = > ' Application/octet-stream ', ' so ' = ' application/octet-stream ', ' dll ' = ' application/octet-stream ', ' ODA ' = > ' Application/oda ', ' pdf ' = ' application/pdf ', ' ai ' = ' application/postscript ', ' eps ' = ' application/ PostScript ', ' ps ' = ' application/postscript ', ' smi ' = ' application/smil ', ' smil ' = ' application/smil ', ' MIF ' = ' application/vnd.mif ', ' xls ' = ' application/vnd.ms-excel ', ' ppt ' = ' application/vnd.ms-powerpoint ', ' Wbxml ' = ' application/vnd.wap.wbxml ', ' wmlc ' = ' application/vnd.wap.wmLC ', ' wmlsc ' = ' APPLICATION/VND.WAP.WMLSCRIPTC ', ' bcpio ' = ' application/x-bcpio ', ' vcd ' = ' application/' X-cdlink ', ' pgn ' = ' application/x-chess-pgn ', ' cpio ' = ' application/x-cpio ', ' csh ' = ' application/x-csh ', ' DCR ' = ' application/x-director ', ' dir ' = ' application/x-director ', ' dxr ' = ' application/x-director ', ' dvi ' = > ' Application/x-dvi ', ' spl ' = ' application/x-futuresplash ', ' gtar ' = ' application/x-gtar ', ' hdf ' and ' = ' APPLICATION/X-HDF ', ' js ' = ' application/x-javascript ', ' skp ' = ' application/x-koan ', ' skd ' = ' application/ X-koan ', ' skt ' = ' application/x-koan ', ' skm ' = ' application/x-koan ', ' latex ' = ' application/x-latex ', ' NC ' =& Gt ' APPLICATION/X-NETCDF ', ' cdf ' = ' application/x-netcdf ', ' sh ' = ' application/x-sh ', ' shar ' = ' application/' X-shar ', ' swf ' = ' application/x-shockwave-flash ', ' sit ' = ' application/x-stuffit ', ' sv4cpio ' = ' application ' /x-sv4cpio ', ' sv4crc ' = ' APPLICATION/X-SV4CRC ', ' tar ' = 'Application/x-tar ', ' tcl ' = ' application/x-tcl ', ' tex ' = ' Application/x-tex ', ' texinfo ' = ' application/' X-texinfo ', ' texi ' = ' application/x-texinfo ', ' t ' = ' application/x-troff ', ' tr ' = ' application/x-troff ', ' Roff ' = ' application/x-troff ', ' man ' = ' application/x-troff-man ', ' me ' = ' application/x-troff-me ', ' ms ' = > ' Application/x-troff-ms ', ' ustar ' = ' application/x-ustar ', ' src ' = ' application/x-wais-source ', ' xhtml ' = > ' Application/xhtml+xml ', ' xht ' = ' application/xhtml+xml ', ' zip ' = ' application/zip ', ' au ' = ' audio/' Basic ', ' snd ' = ' audio/basic ', ' mid ' = ' Audio/midi ', ' midi ' = ' audio/midi ', ' kar ' = ' audio/midi ', ' MPGA ' =&G T ' Audio/mpeg ', ' mp2 ' = ' audio/mpeg ', ' mp3 ' = ' audio/mpeg ', ' aif ' = ' audio/x-aiff ', ' aiff ' = ' Audio/x-aiff ', ' aifc ' = ' audio/x-aiff ', ' m3u ' = ' audio/x-mpegurl ', ' ram ' = ' audio/x-pn-realaudio ', ' rm ' = ' audio/' X-pn-realaudio ', ' rpm ' = ' audio/x-pn-realaudio-plugin ', ' ra ' = ' Audio/x-realaudio ', ' wav ' = ' audio/x-wav ', ' pdb ' = ' chemical/x-pdb ', ' xyz ' = ' chemical/x-xyz ', ' bmp ' = ' I Mage/bmp ', ' gif ' = ' image/gif ', ' ief ' = ' image/ief ', ' jpeg ' = ' image/jpeg ', ' jpg ' = ' image/jpeg ', ' jpe ' = > ' image/jpeg ', ' png ' = ' image/png ', ' tiff ' = ' image/tiff ', ' tif ' = ' image/tiff ', ' djvu ' = ' image/vnd.dj ' Vu ', ' djv ' = ' image/vnd.djvu ', ' wbmp ' = ' image/vnd.wap.wbmp ', ' ras ' = ' image/x-cmu-raster ', ' PNM ' + ' image /x-portable-anymap ', ' PBM ' = ' image/x-portable-bitmap ', ' pgm ' = ' image/x-portable-graymap ', ' ppm ' = ' image/' X-portable-pixmap ', ' rgb ' = ' image/x-rgb ', ' xbm ' = ' image/x-xbitmap ', ' xpm ' = ' image/x-xpixmap ', ' xwd ' and ' = ' Image/x-xwindowdump ', ' igs ' = ' model/iges ', ' iges ' = ' model/iges ', ' msh ' = ' model/mesh ', ' mesh ' = ' model/' Mesh ', ' silo ' = ' model/mesh ', ' wrl ' = ' model/vrml ', ' vrml ' = ' model/vrml ', ' css ' = ' text/css ', ' html ' and ' = ' Text/html ', ' htm ' = ' text/html ', ' ASC ' =&GT ' Text/plain ', ' txt ' = ' text/plain ', ' rtx ' = ' text/richtext ', ' rtf ' = ' text/rtf ', ' sgml ' = ' text/sgml ', ' SGM ' = ' text/sgml ', ' tsv ' = ' text/tab-separated-values ', ' wml ' = ' text/vnd.wap.wml ', ' wmls ' = ' text/' Vnd.wap.wmlscript ', ' etx ' = ' text/x-setext ', ' xsl ' = ' text/xml ', ' xml ' = ' text/xml ', ' mpeg ' = ' video/mpeg ' , ' mpg ' = ' video/mpeg ', ' mpe ' = ' video/mpeg ', ' qt ' = ' video/quicktime ', ' mov ' = ' video/quicktime ', ' Mxu ' =&G T ' Video/vnd.mpegurl ', ' avi ' = ' video/x-msvideo ', ' movie ' = ' Video/x-sgi-movie ', ' ice ' = ' x-conference/ X-cooltalk ', ' rar ' = ' application/x-rar-compressed ', ' zip ' = ' application/x-zip-compressed ', ' * ' and ' = ' Application/octet-stream ', ' docx ' = ' application/msword '); }/** * Open an IMAP stream to a mailbox * * @param string $host * @param string $port * @param string $user * @param stri Ng $pass * @param string $folder * @param string $ssl * @param string $pop * @return Resource|bool */Public functionMailconnect ($host, $port, $user, $pass, $folder = "INBOX", $ssl, $pop =false) {if ($pop) {$ssl = $pop. ' /'. $ssl. ' /novalidate-cert/notls ';} $this->_connect = Imap_open ("{". ") $host: $port/$ssl "."} $folder ", $user, $pass), if (! $this->_connect) {jbxue_application::getsession ()->adderror (' Cannot connect: '). Imap_last_error ()); return false; } return $this->_connect; }/** * Get information about the current mailbox * * @return Object|bool */Public Function Mailinfo () {$this->_mailinf o = Imap_mailboxmsginfo ($this->_connection), if (! $this->_mailinfo) {echo "Get Mailinfo failed:". Imap_last_error (); return false;} return $this->_mailinfo; }/** * Read An overview of the information in the headers of the given message * * @param string $msgRange * @return Arra Y */Public Function maillist ($msgRange = ") {if ($msgRange) {$range = $msgRange;} else {$this->mailtotalcount (); $range = "1:". $this->_totalcount;} $overview = Imap_fetch_overview ($this->_connect, $range); foreach ($overvieW as $val) {$mailList [$val->msgno]= (array) $val;} return $mailList; }/** * Get the total count of the current mailbox * * @return int */Public Function Mailtotalcount () {$check = Imap_check ($this->_connect); $this->_totalcount = $check->nmsgs; return $this->_totalcount; }/** * Read the header of the message * * @param string $msgCount * @return Array */Public function Mailheader ($msgCount {$mailHeader = array (); $header =imap_header ($this->_connect, $msgCount); $sender = $header->from[0]; $replyTo =$ Header->reply_to[0];if (Strtolower ($sender->mailbox)! = ' Mailer-daemon ' && strtolower ($sender- Mailbox)! = ' postmaster ') {$subject = $this->subjectdecode ($header->subject); $mailHeader = Array (' from ' = Strtolower ($sender->mailbox). ' @ '. $sender->host, ' fromname ' = $sender->personal, ' Toother ' =>strtolower ($replyTo->mailbox). ' @ '. $replyTo->host, ' toothername ' = $replyTo->personal, ' subject ' + $subject, ' to ' =>strtolower ($ Header->toaddress), ' date ' = = $header->date, ' id ' = = $header->msgno, ' seen ' + $header->unseen);} return $mailHeader; }/** * Decode the subject of Chinese * * @param string $subject * @return Sting */Public function Subjectdecode ($subject {$beginStr = substr ($subject, 0, 5); if ($beginStr = =? ISO ') {$separator = ' =? ISO-2022-JP '; $toEncoding = ' iso-2022-jp ';} else {$separator = ' =? GB2312 '; $toEncoding = ' GB2312 ';} $encode = Strstr ($subject, $separator), if ($encode) {$explodeArr = explode ($separator, $subject); $length = count ($explod Earr); $SUBJECTARR = Array (); for ($i = 0; $i < $length/2; $i + +) {$SUBJECTARR [$i] = $EXPLODEARR [$i * 2];IF (@ $EXPLODEARR [$i * 2 + 1]) {$subjectAr r[$i] [] = $EXPLODEARR [$i * 2 + 1];} } foreach ($subjectArr as $arr) {$subSubject = implode ($separator, $arr), if (count ($arr) = = 1) {$subSubject = $separator . $subSubject;} $begin = Strpos ($subSubject, "=?"); $end = Strpos ($subSubject, "? ="); $beginStr = "; $endStr ="; if ($end > 0) {if ($begin > 0){$beginStr = substr ($subSubject, 0, $begin);} if ((strlen ($subSubject)-$end) > 2) {$endStr = substr ($subSubject, $end + 2, strlen ($subSubject)-$end-2);} $str = substr ($subSubject, 0, $end-strlen ($subSubject)); $pos = Strrpos ($str, "?"); $str = substr ($str, $pos + 1, strlen ($STR)-$pos); $subSubject = $beginStr. Imap_base64 ($STR). $ENDSTR; $SUBSUBJECTARR [] = Iconv ($toEncoding, ' utf-8 ', $subSubject);//Mb_convert_encoding ($subSubject, ' utf-8 ', ' gb2312, Iso-2022-jp ');} } $subject = Implode ("', $SUBSUBJECTARR);} return $subject; }/** * Mark a message for deletion from current mailbox * * @param string $msgCount */Public function Maildelete ($msgCou NT) {imap_delete ($this->_connect, $msgCount);}/** * Get attach of the message * * @param string $msgCount * @param str ing $path * @return Array */Public function Getattach ($msgCount, $path) {$struckture = Imap_fetchstructure ($this->_con Nect, $msgCount), $attach = Array (), if ($struckture->parts) {foreach ($struckture->pArts as $key = $value) {$encoding = $struckture->parts[$key]->encoding;if ($struckture->parts[$key]-> ifdparameters) {$name = $struckture->parts[$key]->dparameters[0]->value; $message = imap_fetchbody ($this- >_connect, $msgCount, $key + 1); if ($encoding = = 0) {$message = Imap_8bit ($message),} else if ($encoding = = 1) {$message = Imap_8bit ($message);} else if ($encoding = = 2) {$message = Imap_binary ($message);} else if ($encoding = = 3) {$message = Imap_base64 ($message);} else if ($encoding = = 4) {$message = Quoted_printable_decod E ($message); } $this->downattach ($path, $name, $message);; $attach [] = $name;} if ($struckture->parts[$key]->parts) {foreach ($struckture->parts[$key]->parts as $keyb + = $valueb) {$ encoding= $struckture->parts[$key]->parts[$keyb]->encoding;if ($struckture->parts[$key]->parts[$ keyb]->ifdparameters) {$name = $struckture->parts[$key]->parts[$keyb]->dparameters[0]->value; $ Partnro = ($key + 1). ".". ($keyb+1); $message = Imap_fetchbody ($this->_connect, $msgCount, $partnro); if ($encoding = = 0) {$message = Imap_8bit ($message),} else if ($encoding = = 1) {$message = Imap_8bit ($message);} else I F ($encoding = = 2) {$message = Imap_binary ($message),} else if ($encoding = = 3) {$message = Imap_base64 ($message);} El Se if ($encoding = = 4) {$message = Quoted_printable_decode ($message);} $this->downattach ($path, $name, $message); $attach [] = $name;} }} }}

return $attach; }/** * Download the Attach of the mail to localhost * * @param string $filePath * @param string $message * @param string $name */Public Function Downattach ($filePath, $name, $message) {if (Is_dir ($filePath)) {$fileOpen = fopen ($filePath. $ Name, "W");} else {mkdir ($filePath);} Fwrite ($fileOpen, $message); fclose ($fileOpen); }/** * Click the attach link to download the Attach * * @param string $id */Public Function Getattachdata ($id, $filePath, $fileName) {$nameArr = explode ('. ', $fileName); $length = count ($NAMEARR); $contentType = $this->_contenttype[$ namearr[$length -1]];if (! $contentType) {$contentType = $this->_contenttype[' * ');} $filePath = Chop ($filePath); if ($filePath! = ") {if (substr ($filePath, strlen ($filePath) -1,strlen ($filePath)) = = '/') {$filePath. = '/';} $filePath. = $fileName;} else {$filePath = $fileName;} if (!file_exists ($filePath)) {echo ' The file is not Exsit '; return false;} $fileSize = FileSize ($filePath); Header ("Content-type:". $contentType); HeadER ("accept-range:byte"); Header ("Accept-length: $fileSize"); Header ("content-disposition:attachment; Filename= ". $fileName); $fileOpen = fopen ($filePath, "R"); $bufferSize = 1024; $curPos = 0; while (!feof ($fileOpen) && $fileSize-$curPos > $bufferSize) {$buffer = Fread ($fileOpen, $bufferSize); echo $ Buffer $curPos + = $bufferSize;} $buffer = Fread ($fileOpen, $fileSize-$curPos); Echo $buffer; Fclose ($fileOpen); return true; }/** * Get the body of the message * * @param string $msgCount * @return String */Public Function GetBody ($msgCount) {$b Ody = $this->getpart ($msgCount, "text/html"), if ($body = = ") {$body = $this->getpart ($msgCount," Text/plain ");} if ($body = = ") {return ';} return $body; }/** * Read The structure of a particular message and fetch a particular * section of the body of the message * * @param String $msgCount * @param string $mimeType * @param object $structure * @param string $partNumber * @return String|bool * * Private Function GetPart ($msgCount, $miMetype, $structure = False, $partNumber = False) {if (! $structure) {$structure = Imap_fetchstructure ($this->_connect, $ Msgcount);} if ($structure) {if ($mimeType = = $this->getmimetype ($structure)) {if (! $partNumber) {$partNumber = "1";} $fromEncoding = $structure->parameters[0]->value; $text = imap_fetchbody ($this->_connect, $msgCount, $ PartNumber), if ($structure->encoding = = 3) {$text = Imap_base64 ($text),} else if ($structure->encoding = = 4) {$text = Imap_qprint ($text);} $text = mb_convert_encoding ($text, ' utf-8 ', $fromEncoding); return $text; if ($structure->type = = 1) {while (list ($index, $subStructure) = each ($structure->parts)) {if ($partNumber) {$ prefix = $partNumber. '.'; } $data = $this->getpart ($msgCount, $mimeType, $subStructure, $prefix. ($index + 1)); if ($data) {return $data;}} }}return false; }/** * Get the subtype and type of the message structure * * @param object $structure */Private Function GetMimeType ($st ructure) {$mimeType = Array ("TEXT","MULTIPART", "MESSAGE", "Application", "AUDIO", "IMAGE", "VIDEO", "other"), if ($structure->subtype) {return $ mimetype[(int) $structure->type]. '/' . $structure->subtype;} return "Text/plain"; /** * Put the message from unread to read * * @param string $msgCount * @return BOOL */Public Function Mailread ($msgCou NT) {$status = Imap_setflag_full ($this->_connect, $msgCount, "//seen"); return $status;}/** * Close an IMAP stream */ Public Function Closemail () {imap_close ($this->_connect,cl_expunge);}}? >

2, call example and Description 1), Get mailing list

$mailList = Array (), $mail = new Jbxue_email (), $connect = $mail->mailconnect ($this->_imapserver, $this->_port, $this->_email, $this->_password, $this->_floder, $this->_ssl), if ($connect) {    $totalCount = $mail- >mailtotalcount ();    for ($i = $totalCount; $i > 0; $i-) {$mailList [] = $mail->mailheader ($i);    }    $mail->closemail ();}

2), get the message body

$mailId = $this->getrequest ()->getparam (' id '), $mailHeader = Array (); $mailAttach = Array (); $mailBody = "; $mail = New Jbxue_email (); $connect = $mail->mailconnect ($this->_imapserver, $this->_port, $this->_email, $this- >_password, $this->_floder, $this->_ssl), if ($connect) {    $mailHeader = $mail->mailheader ($mailId);    if ($mailHeader [' seen '] = = ' U ') {$mail->mailread ($mailId);    }    $mailBody = $mail->getbody ($mailId);    $mailAttach = $mail->getattach ($mailId, $this->_attachpath);    $mail->closemail ();}

3), download the attachment

$id = $this->getrequest ()->getparam (' id '), $name = $this->getrequest ()->getparam (' name '); $email = new Jbxue_email (); $email->getattachdata ($id, $this->_attachpath, $name);
  • 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.