Php中IMAP应用举例(收发邮件、删除邮件、附件下载)

阅读量:28
2021-04-18
本文介绍下,php中使用IMAP进行收发邮件、删除邮件以及附件下载的例子,有需要的朋友,参考下吧。

php中Imap实例完整代码,如下:

复制代码 代码示例:


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

/**
* 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 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' => '/andrew-inset','hqx' => '/mac-binhex40',
'cpt' => '/mac-compactpro','doc' => '/msword',
'bin' => '/octet-stream','dms' => '/octet-stream',
'lha' => '/octet-stream','lzh' => '/octet-stream',
'exe' => '/octet-stream','class' => '/octet-stream',
'so' => '/octet-stream','dll' => '/octet-stream',
'oda' => '/oda','pdf' => '/pdf',
'ai' => '/postscript','eps' => '/postscript',
'ps' => '/postscript','smi' => '/smil',
'smil' => '/smil','mif' => '/vnd.mif',
'xls' => '/vnd.ms-excel','ppt' => '/vnd.ms-powerpoint',
'wbxml' => '/vnd.wap.wbxml','wmlc' => '/vnd.wap.wmlc',
'wmlsc' => '/vnd.wap.wmlscriptc','bcpio' => '/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',
'sit' => '/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' => '/x-troff-me','ms' => '/x-troff-ms',
'ustar' => '/x-ustar','src' => '/x-wais-source',
'xhtml' => '/xhtml+xml','xht' => '/xhtml+xml',
'zip' => '/zip','au' => '/basic','snd' => '/basic',
'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' => '/mesh','mesh' => '/mesh',
'silo' => '/mesh','wrl' => '/vrml','vrml' => '/vrml',
'css' => '/css','html' => '/html','htm' => '/html',
'asc' => '/plain','txt' => '/plain','rtx' => '/richtext',
'rtf' => '/rtf','sgml' => '/sgml','sgm' => '/sgml',
'tsv' => '/tab-separated-values','wml' => '/vnd.wap.wml',
'wmls' => '/vnd.wap.wmlscript','etx' => '/x-setext',
'xsl' => '/xml','xml' => '/xml','mpeg' => '/mpeg',
'mpg' => '/mpeg','mpe' => '/mpeg','qt' => '/quicktime',
'mov' => '/quicktime','mxu' => '/vnd.mpegurl','avi' => '/x-msvideo',
'movie' => '/x-sgi-movie','ice' => '/x-cooltalk',
'rar' => '/x-rar-compressed','zip' => '/x-zip-compressed',
'*'=> '/octet-stream','docx' => '/msword'
);
}

/**
* Open an IMAP stream to a mailbox
*
* @param string $host
* @param 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.'/notls';
}
$this->_connect = imap_open("{"."$host:$/$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 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($explodeArr);
$subjectArr = array();
for($i = 0; $i 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, "/HTML");
if ($body == '') {
$body = $this->getPart($msgCount, "/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($structure) {
$mimeType = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
if($structure->subtype) {
return $mimeType[(int) $structure->type] . '/' . $structure->subtype;
}
return "/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,调用示例及说明
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);
THE END

发表评论

相关推荐

  • php getdate函数怎么用

    php getdate函数用于返回当前本地的“日期/时间”的“日期/时间”信息,其语法为“getdate(timestamp)”,该函数会返回带有与时间 ...

    阅读量:99
    2021-04-19
  • column的10篇内容推荐

    column-fill属性会将不同高度的指定列以高度差最小化的方式进行对齐,这里我们就来看一下CSS3的column-fill属性对齐列内容高 ...

    阅读量:100
    2021-04-19
  • PHPMailer 中文使用说明小结_PHP教程

    A开头: $AltBody --属性 出自:PHPMailer : $AltBody 文件:class.phpmailer .php 说明:该属性的设置是在邮件正文不支持HT ...

    阅读量:133
    2021-04-19
  • php date与gmdate的获取日期的区别_PHP教程

    date -- 格式化一个本地时间/日期   gmdate -- 格式化一个 /UTC 日期/时间,返回的是格林威治标准时(GMT)。   举个 ...

    阅读量:115
    2021-04-19
  • php 正确解码javascript中通过escape编码后的字符_PHP教程

    这是很久以前收集的一个,不知道谁写的了,但经过测试没有问题~ JavaScript代码

    阅读量:114
    2021-04-19