首頁 >後端開發 >php教程 >Php中IMAP應用範例(收發郵件、刪除郵件、附件下載)

Php中IMAP應用範例(收發郵件、刪除郵件、附件下載)

WBOY
WBOY原創
2016-07-25 08:58:271544瀏覽
本文介紹下,php中使用IMAP進行收發郵件、刪除郵件以及附件下載的例子,有需要的朋友,請參考。

php中Imap實例完整程式碼,如下:

複製程式碼 程式碼範例:

* @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) */

/*** 電子郵件類 * * 取得郵件總數、取得郵件清單、取得郵件內容、取得郵件附件 * * 舉個例子,如果你想取得一些指定的電子郵件清單。 * * $mail = new jbxue_Mail(); * $mail->mailConnect($host,$port,$user,$pass,'INBOX',$ssl); * $mail->mailList('5,9:20'); * * * 顯示五封、九封到二十封郵件。 * * $mail->mailList('5,9:20'); * * * @文檔資訊 * * @package應用程式 * @作者陳喬 * @version $$Id: Email.php 175 2011-03-26 09:52:16Z chen.qiao $$*/ class jbxue_Email { /*** @var資源$_connect*/ private $_connect; /*** @var物件$_mailInfo*/ private $_mailInfo; /*** @var int $_totalCount*/ private $_totalCount; /*** @var數組$_totalCount*/ private $_contentType;

/*** __建構類*/ 公共函數 __construct() { $this->_contentType = 陣列( 'ez' => '應用程式/andrew-inset', 'hqx' => '應用程式/mac-binhex40', 'cpt' => 'application/mac-compactpro','doc' => 'application/msword', 'bin' => '應用程式/八位元組流','dms' => '應用程式/八位元組流', 'lha' => '應用程式/八位元組流','lzh' => '應用程式/八位元組流', 'exe' => '應用程式/八位元組流', 'class' => '應用程式/八位元組流', 'so' => '應用程式/八位元組流','dll' => '應用程式/八位元組流', 'oda' => '應用程式/oda','pdf' => '應用程式/pdf', 'ai' => '應用程式/postscript','eps' => '應用程式/postscript', 'ps' => '應用程式/postscript', 'smi' => '應用程式/smil', 'smil' => '應用程式/smil', 'mif' => '應用程式/vnd.mif', 'xls' => 'application/vnd.ms-excel','ppt' => 'application/vnd.ms-powerpoint', 'wbxml' => '應用程式/vnd.wap.wbxml', 'wmlc' => '應用程式/vnd.wap.wmlc', 'wmlsc' => 'application/vnd.wap.wmlscriptc','bcpio' => 'application/x-bcpio', 'vcd' => '應用程式/x-cdlink','pgn' => '應用程式/x-chess-pgn', 'cpio' => '應用程式/x-cpio','csh' => '應用程式/x-csh', 'dcr' => '應用程式/x-director','dir' => '應用程式/x-director', 'dxr' => '應用程式/x-director','dvi' => '應用程式/x-dvi', 'spl' => '應用程式/x-futuresplash','gtar' => '應用程式/x-gtar', 'hdf' => '應用程式/x-hdf', 'js' => '應用程式/x-javascript', 'skp' => '應用程式/x-koan', 'skd' => '應用程式/x-koan', 'skt' => '應用程式/x-koan', 'skm' => '應用程式/x-koan', 'latex' => '應用程式/x-latex', 'nc' => '應用程式/x-netcdf', 'cdf' => '應用程式/x-netcdf', 'sh' => '應用程式/x-sh', 'shar' => '應用程式/x-shar','swf' => '應用程式/x-shockwave-flash', '坐' => '應用程式/x-stuffit', 'sv4cpio' => '應用程式/x-sv4cpio', 'sv4crc' => '應用程式/x-sv4crc','tar' => '應用程式/x-tar', 'tcl' => '應用程式/x-tcl', 'tex' => '應用程式/x-tex', 'texinfo' => '應用程式/x-texinfo', 'texi' => '應用程式/x-texinfo', 't' => '應用程式/x-troff', 'tr' => '應用程式/x-troff', 'roff' => '應用程式/x-troff', 'man' => '應用程式/x-troff-man', 'me' => 'application/x-troff-me','ms' => 'application/x-troff-ms', 'ustar' => '應用程式/x-ustar', 'src' => '應用程式/x-wais-source', 'xhtml' => '應用程式/xhtml+xml', 'xht' => '應用程式/xhtml+xml', 'zip' => '應用程式/zip','au' => '音訊/基本','snd' => '音訊/基本', 'mid' => '音訊/midi','midi' => '音訊/midi','kar' => '音訊/midi', 'mpga' => '音訊/mpeg','mp2' => '音訊/mpeg','mp3' => '音訊/mpeg', 'aif' => '音訊/x-aiff','aiff' => '音訊/x-aiff','aifc' => '音訊/x-aiff', 'm3u' => '音訊/x-mpegurl','ram' => '音訊/x-pn-realaudio','rm' => '音訊/x-pn-realaudio', 'rpm' => '音訊/x-pn-realaudio-plugin','ra' => '音訊/x-realaudio', 'wav' => '音頻/x-wav','pdb' => '化學/x-pdb','xyz' => '化學/x-xyz', 'bmp' => '圖像/bmp','gif' => '圖像/gif','ief' => '圖像/ief', 'jpeg' => '圖片/jpeg','jpg' => '圖片/jpeg','jpe' => '圖片/jpeg', 'png' => '圖像/png','tiff' => '圖像/tiff','tif' => '圖像/tiff', 'djvu' => '圖片/vnd.djvu','djv' => '圖片/vnd.djvu','wbmp' => '圖片/vnd.wap.wbmp', 'ras' => '影像/x-cmu-raster','pnm' => '影像/x-portable-anymap', 'pbm' => '映像/x-portable-bitmap','pgm' => '映像/x-portable-graymap', 'ppm' => '映像/x-portable-pixmap','rgb' => '映像/x-rgb','xbm' => '影像/x-xbitmap', 'xpm' => '映像/x-xpixmap','xwd' => '映像/x-xwindowdump','igs' => '模型/iges', 'iges' => '模型/iges','msh' => '模型/網格','網格' => '模型/網格', '筒倉' => '模型/網格','wrl' => '模型/vrml','vrml' => '模型/vrml', 'css' => '文字/css','html' => '文字/html','htm' => '文字/html', 'asc' => '文字/純文字','txt' => '文字/純文字','rtx' => '文字/富文本', 'rtf' => '文本/rtf','sgml' => '文本/sgml','sgm' => '文本/sgml', 'tsv' => '文字/製表符分隔值','wml' => '文字/vnd.wap.wml', 'wmls' => 'text/vnd.wap.wmlscript','etx' => 'text/x-settext', 'xsl' => '文字/xml','xml' => '文字/xml','mpeg' => '影片/mpeg', 'mpg' => '影片/mpeg','mpe' => '影片/mpeg','qt' => '影片/quicktime', 'mov' => '影片/quicktime','mxu' => '影片/vnd.mpegurl','avi' => '影片/x-msvideo', '電影' => '視頻/x-sgi-movie','ice' => 'x-conference/x-cooltalk', 'rar' => '應用程式/x-rar-壓縮','zip' => '應用程式/x-zip-壓縮', '*'=> '應用程式/八位元組流','docx' => '應用程式/msword' ); }/*** 開啟到郵件信箱的 IMAP 流 * * @param 字串 $host * @參數字串$端口 * @參數字串$用戶 * @參數字串 $pass * @param 字串$資料夾 * @參數字串$ssl * @param 字串 $pop * @return 資源|bool*/ 公用函數 mailConnect($host,$port,$user,$pass,$folder="INBOX",$ssl,$pop=false) { 如果($流行){ $ssl = $pop.'/'.$ssl.'/novalidate-cert/notls'; } $this->_connect = imap_open("{"."$host:$port/$ssl"."}$folder",$user,$pass); if(!$this->_connect) { jbxue_Application::getSession()->addError('無法連線:' . imap_last_error()); 返回假; } 返回 $this->_connect; } /*** 取得目前信箱信息 * * @return 物件|布爾*/ 公共函數mailInfo(){ $this->_mailInfo = imap_mailboxmsginfo($this->_connection); if(!$this->_mailInfo) { echo「取得郵件資訊失敗:」。 imap_last_error(); 返回假; } 返回$this->_mailInfo; } /*** 閱讀給定訊息標題中的信息概述 * * @param 字串 $msgRange * @返回數組*/ 公用函數mailList($msgRange='') { 如果($msgRange){ $範圍=$msgRange; } 別的 { $this->mailTotalCount(); $range = "1:".$this->_totalCount; } $overview = imap_fetch_overview($this->_connect,$range); foreach ($overview as $val) { $mailList[$val->msgno]=(數組)$val; } 返回$mailList; } /*** 取得目前信箱總數 * * @傳回整數*/ 公用函數 mailTotalCount(){ $check = imap_check($this->_connect); $this->_totalCount = $check->Nmsgs; 返回$this->_totalCount; } /*** 讀取訊息的標題 * * @參數字串$msgCount * @返回數組*/ 公用函數 mailHeader($msgCount) { $mailHeader = 數組(); $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 = 陣列( 'from'=>strtolower($sender->郵箱).'@'.$sender->主機, 'fromName'=>$sender->個人, 'toOther'=>strtolower($replyTo->信箱).'@'.$replyTo->主機, 'toOtherName'=>$replyTo->個人, '主題'=>$主題, 'to'=>strtolower($header->toaddress), '日期'=>$header->日期, 'id'=>$header->Msgno, '已見'=>$header->未見 ); } 返回$mailHeader; } /*** 解碼中文主語 * * @param 字串 $subject * @return 刺*/ 公用函數 subjectDecode($subject) { $beginStr = substr($subject, 0, 5); if($beginStr == '=?ISO') { $separator = '=?ISO-2022-JP'; $toEncoding = 'ISO-2022-JP'; } 別的 { $separator = '=?GB2312'; $toEncoding = 'GB2312'; } $encode = strstr($subject, $separator); 如果($編碼){ $explodeArr = 爆炸($separator, $subject); $length = count($explodeArr); $subjectArr = 陣列(); for($i = 0; $i 0) { 如果($開始> 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 = 內爆('', $subSubjectArr); } 返回$主題; } /*** 將郵件標記為從目前信箱中刪除 * * @參數字串$msgCount*/ 公用函數 mailDelete($msgCount) { imap_delete($this->_connect,$msgCount); } /*** 取得訊息的附件 * * @參數字串$msgCount * @參數字串$路徑 * @返回數組*/ 公用函數 getAttach($msgCount,$path) { $struckture = imap_fetchstruct($this->_connect,$msgCount); $附加=陣列(); if($結構->零件) { foreach($structure->parts as $key => $value) { $encoding=$struckture->parts[$key]->encoding; if($structure->parts[$key]->ifdparameters) { $name=$struckture->parts[$key]->dparameters[0]->value; $message = imap_fetchbody($this->_connect,$msgCount,$key+1); 如果($編碼== 0){ $message = imap_8bit($message); }否則如果($編碼== 1){ $message = imap_8bit ($message); } 否則 if ($encoding == 2) { $message = imap_binary ($message); } else if ($encoding == 3) { $message = imap_base64 ($message); } 否則 if ($encoding == 4) { $message = Quoted_printable_decode($message); } $this->downAttach($路徑,$名稱,$訊息);; $attach[] = $名稱; } if($struct->parts[$key]->parts) { foreach($struct->parts[$key]->parts as $keyb => $valueb) { $encoding=$struckture->parts[$key]->parts[$keyb]->encoding; if($struct->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); 如果($編碼== 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); } 否則 if ($encoding == 4) { $message = Quoted_printable_decode($message); } $this->downAttach($路徑,$名稱,$訊息); $attach[] = $名稱; } } } } }

返回$attach; } /*** 下載郵件附件到本機 * * @param 字串 $filePath * @param 字串$訊息 * @param 字串 $name*/ 公用函數 downAttach($filePath,$name,$message) { if(is_dir($filePath)) { $fileOpen = fopen($filePath.$name,"w"); } 別的 { mkdir($檔路徑); } fwrite($fileOpen,$message); fclose($fileOpen); } /*** 點選附件連結下載附件 * * @param 字串 $id*/ 公用函數 getAttachData($id,$filePath,$fileName) { $nameArr = 爆炸('.',$fileName); $length = count($nameArr); $contentType = $this->_contentType[$nameArr[$length-1]]; if(!$contentType) { $contentType = $this->_contentType['*']; } $filePath = 斬($filePath); if($filePath!= ''){ if(substr($filePath,strlen($filePath)-1,strlen($filePath)) != '/') { $filePath .= '/'; } $filePath .= $fileName; } 別的 { $檔案路徑 = $檔案名稱; } if(!file_exists($filePath)){ echo '檔案不存在'; 返回假; } $fileSize = 檔案大小($filePath); header("內容類型:".$contentType); header("接受範圍:位元組"); header("接受長度:$fileSize"); header("內容配置:附件;檔案名稱=".$fileName); $fileOpen= fopen($filePath,"r"); $緩衝區大小= 1024; $curPos = 0; while(!feof($fileOpen)&&$fileSize-$curPos>$bufferSize) { $buffer = fread($fileOpen,$bufferSize); 回顯$緩衝區; $curPos += $bufferSize; } $buffer = fread($fileOpen,$fileSize-$curPos); 回顯$緩衝區; fclose($fileOpen); 返回真; } /*** 取得訊息正文 * * @參數字串$msgCount * @返回字串*/ 公用函數 getBody($msgCount) { $body = $this->getPart($msgCount, "TEXT/HTML"); 如果($body==''){ $body = $this->getPart($msgCount, "TEXT/PLAIN"); } 如果($body==''){ 返回 '​​'; } 返回$body; } /*** 讀取特定訊息的結構並取得特定的 * 訊息正文部分 * * @參數字串$msgCount * @param 字串 $mimeType * @param物件$結構 * @param 字串 $partNumber * @return 字串|布林值*/ 私有函數 getPart($msgCount, $mimeType, $struct = false, $partNumber = false) { if(!$結構) { $struct = imap_fetchstruct($this->_connect, $msgCount); } 如果($結構){ if($mimeType == $this->getMimeType($struct)) { if(!$partNumber) { $零件編號 = "1"; } $fromEncoding = $結構->參數[0]->值; $text = imap_fetchbody($this->_connect, $msgCount, $partNumber); if($結構->編碼 == 3) { $text = imap_base64($text); } else if($struct->encoding == 4) { $text = imap_qprint($text); } $text = mb_convert_encoding($text,'utf-8',$fromEncoding); 返回$文本; } if($結構->類型 == 1) { while(列表($index, $subStructure) = every($struct->parts)) { if($partNumber) { $前綴 = $partNumber 。 '.'; } $data = $this->getPart($msgCount, $mimeType, $subStructure, $prefix . ($index + 1)); 如果($數據){ 返回$數據; } } } } 返回假; } /*** 取得訊息結構體的子類型和類型 * * @param物件$結構*/ 私有函數 getMimeType($struct) { $mimeType = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER"); if($結構->子類型) { 返回 $mimeType[(int) $struct->type] 。 '/' 。 $結構->子類型; } 返回“文字/純文字”; } /*** 將訊息從未讀改為已讀 * * @參數字串$msgCount * @返回布林值*/ 公用函數 mailRead($msgCount) { $status = imap_setflag_full($this->_connect, $msgCount , "//已檢視"); 返回$狀態; } /*** 關閉 IMAP 流*/ 公共函數 closeMail() { imap_close($this->_connect,CL_EXPUNGE); } } ?>

2,呼叫範例及說明 1),取得郵件列表

$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),取得郵件正文

$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),下載附件

$id = $this->getRequest()->getParam('id');
$name = $this->getRequest()->getParam('name');
$email = new jbxue_Email();
$email->getAttachData($id,$this->_attachPath,$name);


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn