侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

PHP receiveMail实现收邮件功能

php  /  管理员 发布于 7年前   2446

用PHP来发邮件,相信大家都不陌生,但读取收件箱的话,接触就少了,这次总结下自己的经验,希望可以帮助大家.

注意:

1.PHP读取收件箱主要是利用imap扩展,所以在使用以下方法前,必须开启imap扩展模块的支持.

2.此方法支持中文,不会乱码,需要保持所有文件的编码的一致性

1.文件结构

2.邮件类 ./mailreceived/receiveMail.class.php

./mailreceived/receiveMail.class.php 文件内容如下:

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->marubox)     {       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->marubox,$mid);     $sender=$mail_header->from[0];     $sender_replyto=$mail_header->reply_to[0];     if(strtolower($sender->mailbox)!='mailer-daemon' && strtolower($sender->mailbox)!='postmaster')     {       $subject=$this->decode_mime($mail_header->subject);        $ccList=array();       foreach ($mail_header->cc as $k => $v)       {         $ccList[]=$v->mailbox.'@'.$v->host;       }       $toList=array();       foreach ($mail_header->to as $k => $v)       {         $toList[]=$v->mailbox.'@'.$v->host;       }       $ccList=implode(",", $ccList);       $toList=implode(",", $toList);       $mail_details=array(           'fromBy'=>strtolower($sender->mailbox).'@'.$sender->host,           'fromName'=>$this->decode_mime($sender->personal),           'ccList'=>$ccList,//strtolower($sender_replyto->mailbox).'@'.$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]->mailbox).'@'.$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, $msg_number, $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','utf8',$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, $msg_number, $mime_type, $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->marubox,$mid);          $files=array();     if($struckture->parts)     {       foreach($struckture->parts as $key => $value)       {         $enc=$struckture->parts[$key]->encoding;      //取邮件附件         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->marubox,$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)//图片 $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);        }         // 处理内容中包含图片的部分         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) {   //命名图片   $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->marubox,$mid,$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 taskMailBox     $this->move_mails($mid, $this->marubox);         return $files;   }      function getBody($mid,&$path,$imageList) // Get Message Body   {     if(!$this->marubox)       return false;      $body = $this->get_part($this->marubox, $mid, "TEXT/HTML");     if ($body == "")       $body = $this->get_part($this->marubox, $mid, "TEXT/PLAIN");     if ($body == "") {        return "";     }     //处理图片     $body=$this->embed_images($body,$path,$imageList);     return $body;   }      function embed_images(&$body,&$path,$imageList)   {     // get all img tags     preg_match_all('//', $body, $matches);     if (!isset($matches[0])) return;          foreach ($matches[0] as $img)     {       // replace image web path with local path       preg_match('/src="https:/article/(.*?)"/', $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->marubox,$mid);   }   function close_mailbox() //Close Mail Box   {     if(!$this->marubox)       return false;      imap_close($this->marubox,CL_EXPUNGE);   }      //移动邮件到指定分组   function move_mails($msglist,$mailbox)   {     if(!$this->marubox)       return false;        imap_mail_move($this->marubox, $msglist, $mailbox);   }      function creat_mailbox($mailbox)   {     if(!$this->marubox)       return false;          //imap_renamemailbox($imap_stream, $old_mbox, $new_mbox);     imap_create($this->marubox, $mailbox);   }      /*    * 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,'utf8',$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 内容如下:

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 Box     $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 box     $tot=$obj->getTotalMails(); //Total Mails in Inbox Return integer value     if($tot < 1) { //如果信件数为0,显示信息       return array("msg"=>"No Message for ".$this->mailAccount);     }     else     {       $res=array("msg"=>"Total Mails:: $tot
"); 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) //处理邮件附件 $files=$obj->GetAttach($i,$this->savePath); // 获取邮件附件,返回的邮件附件信息数组 $imageList=array(); foreach($files as $k => $file) { //type=1为附件,0为邮件内容图片 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,$this->mailPasswd,$this->mailAddress,$this->mailServer,$this->serverType,$this->port,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);      //创建邮箱 // $obj->creatBox("readyBox"); ?> 

4.访问地址:http://localhost/test.cn/mailreceived/mailControl.php 即可

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:

  • PHPMailer使用教程(PHPMailer发送邮件实例分析)
  • php邮件发送的两种方式
  • 功能齐全的PHP发送邮件类代码附详细说明
  • php中通过smtp发邮件的类,测试通过
  • php邮件发送,php发送邮件的类
  • PHPMailer邮件类利用smtp.163.com发送邮件方法
  • phpmailer在服务器上不能正常发送邮件的解决办法
  • phpmailer简单发送邮件的方法(附phpmailer源码下载)
  • php中mail函数发送邮件失败的解决方法
  • php下使用SMTP发邮件的代码


  • 上一条:
    PHP分享图片的生成方法
    下一条:
    原生php实现excel文件读写的方法分析
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客