PHP receiveMail实现收邮件功能


Posted in PHP onApril 25, 2018

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

注意:

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

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

1.文件结构

PHP receiveMail实现收邮件功能

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

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

<?php 
// Main ReciveMail Class File - Version 1.0 (03-06-2015) 
/* 
 * File: recivemail.class.php 
 * Description: Reciving mail With Attechment 
 * Version: 1.1 
 * Created: 03-06-2015 
 * Author: Sara Zhou 
 */ 
class receiveMail 
{ 
  var $server=''; 
  var $username=''; 
  var $password=''; 
   
  var $marubox='';           
   
  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->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('/<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, '<img alt="" src="'.$path.$imageList[$filename[0]].'" style="border: none;" />', $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 内容如下:

<? 
/* 
 * File: mailControl.php 
 * Description: Received Mail Example 
 * Created: 03-06-2015 
 * Author: Sara Zhou 
 */ 
@header('Content-type: text/html;charset=UTF-8'); 
error_reporting(0); 
ignore_user_abort(); // run script in background 
set_time_limit(0); // run script forever 
date_default_timezone_set('Asia/Shanghai'); 
include("receivemail.class.php"); 
class mailControl 
{ 
  //定义系统常量 
  //用户名 
  public $mailAccount = "123456@qq.com"; 
  public $mailPasswd = "12345"; 
  public $mailAddress = "123456@qq.com"; 
  public $mailServer = "pop.qq.com"; 
  public $serverType = "pop3"; 
  public $port = "110"; 
  public $now    = 0; 
  public $savePath = ''; 
  public $webPath  = "../upload/"; 
   
  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 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<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) 
     
        //处理邮件附件 
        $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 "<pre>";print_r($res); 
   
  //创建邮箱 
// $obj->creatBox("readyBox"); 
?>

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

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

PHP 相关文章推荐
php xfocus防注入资料
Apr 27 PHP
php中突破基于HTTP_REFERER的防盗链措施(stream_context_create)
Mar 29 PHP
php操作mysql数据库的基本类代码
Feb 25 PHP
php多功能图片处理类分享(php图片缩放类)
Mar 14 PHP
destoon出现验证码不显示时的紧急处理方法
Aug 22 PHP
php操作redis缓存方法分享
Jun 03 PHP
PHP的Yii框架中YiiBase入口类的扩展写法示例
Mar 17 PHP
PHP 实现浏览记录并按日期分组
May 11 PHP
PHP重置数组为连续数字索引的几种方式总结
Mar 12 PHP
PHP自动载入类文件函数__autoload的使用方法
Mar 25 PHP
Laravel关系模型指定条件查询方法
Oct 10 PHP
Swoole扩展的6种模式深入详解
Mar 04 PHP
laravel中短信发送验证码的实现方法
Apr 25 #PHP
PHP设计模式之适配器模式原理与用法分析
Apr 25 #PHP
PHP设计模式之原型设计模式原理与用法分析
Apr 25 #PHP
PHP设计模式之单例模式原理与实现方法分析
Apr 25 #PHP
PHP设计模式之工厂方法设计模式实例分析
Apr 25 #PHP
原生php实现excel文件读写的方法分析
Apr 25 #PHP
PHP操作Redis常用技巧总结
Apr 24 #PHP
You might like
转换中文日期的PHP程序
2006/10/09 PHP
php的socket编程详解
2016/11/20 PHP
Ajax中的JSON格式与php传输过程全面解析
2017/11/14 PHP
tp5(thinkPHP5)操作mongoDB数据库的方法
2018/01/20 PHP
php中目录操作opendir()、readdir()及scandir()用法示例
2019/06/08 PHP
Jquery提交表单 Form.js官方插件介绍
2012/03/01 Javascript
javascript针对DOM的应用分析(四)
2012/04/15 Javascript
表头固定(利用jquery实现原理介绍)
2012/11/08 Javascript
Javascript和HTML5利用canvas构建Web五子棋游戏实现算法
2013/07/17 Javascript
jquery退出each循环的写法
2014/02/26 Javascript
JavaScript实现添加及删除事件的方法小结
2015/08/04 Javascript
基于html5和nodejs相结合实现websocket即使通讯
2015/11/19 NodeJs
js实现的二分查找算法实例
2016/01/21 Javascript
js轮盘抽奖实例分析
2020/04/17 Javascript
利用bootstrapValidator验证UEditor
2016/09/14 Javascript
jQuery简单实现MD5加密的方法
2017/03/03 Javascript
Vue.js仿Metronic高级表格(一)静态设计
2017/04/17 Javascript
jQuery使用JSONP实现跨域获取数据的三种方法详解
2017/05/04 jQuery
微信小程序城市定位的实现实例(获取当前所在国家城市信息)
2017/05/17 Javascript
js实现方块上下左右移动效果
2017/08/17 Javascript
JavaScript实现的超简单计算器功能示例
2017/12/23 Javascript
打通前后端构建一个Vue+Express的开发环境
2018/07/17 Javascript
[03:53]2016国际邀请赛中国区预选赛第三日TOP10精彩集锦
2016/06/29 DOTA
python插入排序算法的实现代码
2013/11/21 Python
Python中使用ElementTree解析XML示例
2015/06/02 Python
Python双向循环链表实现方法分析
2018/07/30 Python
Pycharm设置去除显示的波浪线方法
2018/10/28 Python
在pycharm中设置显示行数的方法
2019/01/16 Python
Django Admin中增加导出Excel功能过程解析
2019/09/04 Python
python GUI库图形界面开发之PyQt5窗口背景与不规则窗口实例
2020/02/25 Python
初中物理教学反思
2014/01/14 职场文书
孝老爱亲模范事迹材料
2014/05/25 职场文书
初中信息技术教学计划
2015/01/22 职场文书
2015年教师节贺卡寄语
2015/03/24 职场文书
标会主持词应该怎么写?
2019/08/15 职场文书
「Manga Time Kirara MAX」2022年5月号封面公开
2022/03/21 日漫