用PHP来发邮件,相信大家都不陌生,但读取收件箱的话,接触就少了,这次总结下自己的经验,希望可以帮助大家.
注意:
1.PHP读取收件箱主要是利用imap扩展,所以在使用以下方法前,必须开启imap扩展模块的支持.
2.此方法支持中文,不会乱码,需要保持所有文件的编码的一致性
1.文件结构
2.邮件类
./mailreceived/receiveMail.class.PHP./mailreceived/receiveMail.class.PHP 文件内容如下:
var $email='';
function receiveMail($username,$password,$EmailAddress,$mailserver='localhost',$servertype='pop',$port='110',$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->maruBox=@imap_open($this->server,$this->username,$this->password);
if(!$this->maru<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>)
{
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->maru<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>,$mid);
$sender=$mail_header->from[0];
$sender_replyto=$mail_header->reply_to[0];
if(strtolower($sender->mail<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>)!='mailer-daemon' && strtolower($sender->mail<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>)!='postmaster')
{
$subject=$this->decode_mime($mail_header->subject);
$ccList=array();
foreach ($mail_header->cc as $k => $v)
{
$ccList[]=$v->mail<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>.'@'.$v->host;
}
$toList=array();
foreach ($mail_header->to as $k => $v)
{
$toList[]=$v->mail<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>.'@'.$v->host;
}
$ccList=implode(",",$ccList);
$toList=implode(",$toList);
$mail_details=array(
'fromBy'=>strtolower($sender->mail<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>).'@'.$sender->host,'fromName'=>$this->decode_mime($sender->personal),'ccList'=>$ccList,//strtolower($sender_replyto->mail<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>).'@'.$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]->mail<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>).'@'.$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","MULTIPART","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 Internal Private Use
{
if(!$structure) {
$structure = imap_fetchstructure($stream,$msg_number);
}
if($structure) {
if($mime_type == $this->get_mime_type($structure))
{
if(!$part_number)
{
$part_number = "1";
}
$text = imap_fetchbody($stream,$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',$text);
}
}
if($structure->type == 1) / multipart /
{
while(list($index,$sub_structure) = each($structure->parts))
{
if($part_number)
{
$prefix = $part_number . '.';
}
$data = $this->get_part($stream,$sub_structure,$prefix . ($index + 1));
if($data)
{
return $data;
}
}
}
}
return false;
}
function getTotalMails() //Get Total Number off Unread Email In MailBox
{
if(!$this->maruBox)
return false;
// return imap_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->maru<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>,$mid);
$files=array();
if($struckture->parts)
{
foreach($struckture->parts as $key => $value)
{
$enc=$struckture->parts[$key]->encoding;
//取<a href="https://www.jb51.cc/tag/youjian/" target="_blank" class="keywords">邮件</a>附件
if($struckture->parts[$key]->ifdparameters)
{
//命名附件,转码
$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->maru<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>,$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)//<a href="https://www.jb51.cc/tag/tupian/" target="_blank" class="keywords">图片</a>
$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);
}
// 处理<a href="https://www.jb51.cc/tag/neirong/" target="_blank" class="keywords">内容</a>中包含<a href="https://www.jb51.cc/tag/tupian/" target="_blank" class="keywords">图片</a>的部分
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)
{
//命名<a href="https://www.jb51.cc/tag/tupian/" target="_blank" class="keywords">图片</a>
$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->maru<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>,$partnro);
if ($enc == 0)
$message = imap_8bit($message);
if ($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 = $message;
$fp=fopen($path.$file['pathname'],"w");
fwrite($fp,$message);
fclose($fp);
}
}
}
}
}
//move mail to taskMail<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>
$this->move_mails($mid,$this->maru<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>);
return $files;
}
function getBody($mid,&$path,$imageList) // Get Message Body
{
if(!$this->maruBox)
return false;
$body = $this->get_part($this->maru<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>,"TEXT/HTML");
if ($body == "")
$body = $this->get_part($this->maru<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>,"TEXT/PLAIN");
if ($body == "") {
return "";
}
//处理<a href="https://www.jb51.cc/tag/tupian/" target="_blank" class="keywords">图片</a>
$body=$this->embed_images($body,$path,$imageList);
return $body;
}
function embed_images(&$body,$imageList)
{
// get all img tags
preg_match_all('/<img.*?>/',$body,$matches);
if (!isset($matches[0])) return;
foreach ($matches[0] as $img)
{
// replace image web path with local path
preg_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,'',$body);
}
}
return $body;
}
function deleteMails($mid) // Delete That Mail
{
if(!$this->maruBox)
return false;
imap_delete($this->maru<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>,$mid);
}
function close_mailBox() //Close Mail Box
{
if(!$this->maruBox)
return false;
imap_close($this->maru<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>,CL_EXPUNGE);
}
//移动邮件到指定分组
function move_mails($msglist,$mailBox)
{
if(!$this->maruBox)
return false;
imap_mail_move($this->maru<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>,$msglist,$mail<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>);
}
function creat_mailBox($mailBox)
{
if(!$this->maruBox)
return false;
//imap_renamemail<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>($imap_stream,$old_m<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>,$new_m<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>);
imap_create($this->maru<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>,$mail<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>);
}
/*
- decode_mime()转换邮件标题的字符编码,处理乱码
*/
function decode_mime($str){
$str=imap_mime_header_decode($str);
return $str[0]->text;
echo "str";print_r($str);
if ($str[0]->charset!="default")
{echo "==".$str[0]->text;
return iconv($str[0]->charset,$str[0]->text);
}
else
{
return $str[0]->text;
}
}
/**
- Set path name of the uploaded file to be saved.
- @param int $fileID
- @param string $extension
- @access public
- @return string
*/
public function setPathName($fileID,$extension)
{
return date('Ym/dHis',time()) . $fileID . mt_rand(0,10000) . '.' . $extension;
}
}
?>
3.控制层
./mailreceived/mailControl.PHP./mailreceived/mailControl.PHP 内容如下:
public function __construct()
{
$this->now = date("Y-m-d H:i:s",time());
$this->setSavePath();
}
/**
- mail Received()读取收件箱邮件
- @param
- @access public
- @return result
*/
public function mailReceived()
{
// Creating a object of reciveMail Class
$obj= new receivemail($this->mailAccount,$this->mailPasswd,$this->mailAddress,$this->mailServer,$this->serverType,$this->port,false);
//Connect to the Mail <a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>
$res=$obj->connect(); //If connection fails give error message and exit
if (!$res)
{
return array("msg"=>"Error: Connecting to mail server");
}
// Get Total Number of Unread Email in mail <a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a>
$tot=$obj->getTotalMails(); //Total Mails in In<a href="https://www.jb51.cc/tag/Box/" target="_blank" class="keywords">Box</a> Return integer value
if($tot < 1) { //如果信件数为0,显示信息
return array("msg"=>"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 are (subject,to,toOth,toNameOth,from,fromName)
//处理<a href="https://www.jb51.cc/tag/youjian/" target="_blank" class="keywords">邮件</a>附件
$files=$obj->GetAttach($i,$this->savePath); // <a href="https://www.jb51.cc/tag/huoqu/" target="_blank" class="keywords">获取</a><a href="https://www.jb51.cc/tag/youjian/" target="_blank" class="keywords">邮件</a>附件,返回的<a href="https://www.jb51.cc/tag/youjian/" target="_blank" class="keywords">邮件</a>附件信息数组
$imageList=array();
foreach($files as $k => $file)
{
//type=1为附件,0为<a href="https://www.jb51.cc/tag/youjian/" target="_blank" class="keywords">邮件</a><a href="https://www.jb51.cc/tag/neirong/" target="_blank" class="keywords">内容</a><a href="https://www.jb51.cc/tag/tupian/" target="_blank" class="keywords">图片</a>
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 Box
return $res;
}
}
/**
- creatBox
- @access public
- @return void
*/
public function creatBox($BoxName)
{
// Creating a object of reciveMail Class
$obj= new receivemail($this->mailAccount,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();
//收取邮件
$res=$obj->mailReceived();
echo "
";print_r($res);
4.访问地址:http://localhost/test.cn/mailreceived/mailControl.PHP 即可
原文链接:https://www.f2er.com/php/16109.html