Example of IMAP application in Php (sending and receiving emails, deleting emails, and downloading attachments)-php Tutorial

Source: Internet
Author: User
Tags imap gtar
Example of IMAP application in Php (sending and receiving emails, deleting emails, and downloading attachments)
This article describes how to use IMAP in php to send and receive emails, delete emails, and download attachments. For more information, see.

The complete code of the Imap instance in php is as follows:

Sample code:

* @ Version $ Id: Email. php 175 2011-03-26 09: 52: 16Z chen. qiao $ * @ copyright Copyright (c) 2011 jbxue Inc. China (http://bbs.it-home.org )*/

/*** Email class ** get mail total count, get mail list, get mail content, get mail attach ** For a example, if you want 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 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 '=> 'applicatio N/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/smi', 'smi' => 'application/smi', 'MI' => 'application/vnd. mif ', 'XLS' => 'application/vnd. m S-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-ctor', 'dir' => 'application/x-directo R', 'dxr' => 'application/x-ctor ', 'dvi' => 'application/x-dvi ', 'spl' => 'application/x-futuresplash ', 'gtar' => 'application/x-gtar', 'hdf' => 'application/x-hdf ', 'js' => 'application/x-javascript ', 'skp' => 'application/x-koan', 'skd' => 'application/x-koan ', 'skt' => 'application/x-koanc', 'skm' => 'application/x-koanc', 'latex '=> 'application/x-latex ', 'NC '=> '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', 'textinfo' => 'application/x-texinfo', 'text' => 'application/x-texinfo ', 'T' => 'AP Plication/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 ', 'M ID' => 'audio/midi ', 'midi' => 'audio/midi ', 'Kar' => 'audio/midi ', 'mpga' => '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 ', 'A' => 'Audio'/x-realaudio', 'wav '=> 'Audio'/x-wav', 'pdb' => 'Chemical/x-pdb', 'XYZ' => 'chemical/x-XYZ', 'bmp '=> 'image/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. djvu ', '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' => 'image/x-xwindowdump ', 'gies' => 'model/iges', 'iges' => 'model/iges ', 'msh' => 'model/mesh ', 'mesh '=> 'model/mesh', 'silo' => 'model/mesh ', 'wrl' => 'model/PA ', 'text' => 'model/XML', 'css '=> 'text/css', 'html' => 'Text/html', 'htm' => 'text/html', 'asc '=> 'text/plain', 'txt '=> 'text/plain ', 'rtx' => 'text/richtext', 'text' => 'text/text', 'sgml' => 'text/sgml ', 'sgm' => 'text/sgml', 'tsv' => 'text/tab-separated-values', 'wm' => '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/mp Eg ', 'qt' => 'video/quicktime', 'mov '=> 'video/quicktime', 'mxu' => 'video/vnd. mpegurl', 'Av' => 'video/x-msvideo', 'movi' => 'video/x-sgi-movie ', 'Ice '=> 'X-conference/x-cooltalk', 'rar '=> 'application/x-rar-compressed ', 'Zip' => 'application/x-zip-compressed ',' * '=> 'application/octet-stream ', 'docx' => 'application/msword');}/*** Open an IMAP stream to a mailbox ** @ param string $ host * @ par Am string $ port * @ param string $ user * @ param string $ pass * @ param string $ folder * @ param string $ ssl * @ param string $ pop * @ return resource | bool */public function mailConnect ($ 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-> _ mailInfo = 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 array */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 ar Ray */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, 'subobject' => $ 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 ($ explodeArr); $ subjectArr = array (); for ($ I = 0; $ I <$ length/2; $ I ++) {$ subjectArr [$ I] [] = $ explodeArr [$ I * 2]; if (@ $ explodeArr [$ I * 2 + 1]) {$ subjectArr [$ I] [] = $ explodeArr [$ I * 2 + 1] ;}} foreach ($ subjectArr as $ arr) {$ subSubject = implode ($ separ Ator, $ 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 ($ msgCount) {imap_delete ($ this-> _ connect, $ msgCount);}/*** get attach of the message ** @ param string $ msgCount * @ param string $ path * @ return array */public function getAttach ($ msgCount, $ path) {$ struckture = imap_fetchstructure ($ this-> _ connect, $ 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_decode ($ 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 if ($ encoding = 2) {$ message = imap_binary ($ message);} else if ($ encoding = 3) {$ message = imap_base64 ($ message);} else 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) {$ body = $ this-> getPart ($ msgCount, "TEXT/HTML"); if ($ body ='') {$ Body = $ this-> getPart ($ msgCount, "TEXT/PLAIN");} if ($ body = '') {return '';} return $ body ;} /*** Read the structure of a participant message and fetch a participant * 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, $ subStruc Ture) = 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 ($ structure) {$ mimeType = array ("TEXT ", "MULTIPART", "MESSAGE", "APPLIC ATION "," 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 ($ msgCount) {$ 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) to obtain the email 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 mail 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);

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.