登录  /  注册

PHP receiveMail实现收邮件功能

不言
发布: 2018-04-26 11:41:30
原创
2682人浏览过

这篇文章主要为大家详细介绍了php receivemail实现收邮件功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

注意:

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

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

1.文件结构

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=&#39;&#39;; 
  var $username=&#39;&#39;; 
  var $password=&#39;&#39;; 
   
  var $marubox=&#39;&#39;;           
   
  var $email=&#39;&#39;;    
   
  function receiveMail($username,$password,$EmailAddress,$mailserver=&#39;localhost&#39;,$servertype=&#39;pop&#39;,$port=&#39;110&#39;,$ssl = false) //Constructure 
  { 
    if($servertype==&#39;imap&#39;) 
    { 
      if($port==&#39;&#39;) $port=&#39;143&#39;;  
      $strConnect=&#39;{&#39;.$mailserver.&#39;:&#39;.$port. &#39;}INBOX&#39;;  
    } 
    else 
    { 
      $strConnect=&#39;{&#39;.$mailserver.&#39;:&#39;.$port. &#39;/pop3&#39;.($ssl ? "/ssl" : "").&#39;}INBOX&#39;;  
    } 
    $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)!=&#39;mailer-daemon&#39; && strtolower($sender->mailbox)!=&#39;postmaster&#39;) 
    { 
      $subject=$this->decode_mime($mail_header->subject); 
 
      $ccList=array(); 
      foreach ($mail_header->cc as $k => $v) 
      { 
        $ccList[]=$v->mailbox.&#39;@&#39;.$v->host; 
      } 
      $toList=array(); 
      foreach ($mail_header->to as $k => $v) 
      { 
        $toList[]=$v->mailbox.&#39;@&#39;.$v->host; 
      } 
      $ccList=implode(",", $ccList); 
      $toList=implode(",", $toList); 
      $mail_details=array( 
          &#39;fromBy&#39;=>strtolower($sender->mailbox).&#39;@&#39;.$sender->host, 
          &#39;fromName&#39;=>$this->decode_mime($sender->personal), 
          &#39;ccList&#39;=>$ccList,//strtolower($sender_replyto->mailbox).&#39;@&#39;.$sender_replyto->host, 
          &#39;toNameOth&#39;=>$this->decode_mime($sender_replyto->personal), 
          &#39;subject&#39;=>$subject, 
          &#39;mailDate&#39;=>date("Y-m-d H:i:s",$mail_header->udate), 
          &#39;udate&#39;=>$mail_header->udate, 
          &#39;toList&#39;=>$toList//strtolower($mail_header->to[0]->mailbox).&#39;@&#39;.$mail_header->to[0]->host 
//         &#39;to&#39;=>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] . &#39;/&#39; . $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(&#39;gb2312&#39;,&#39;utf8&#39;,imap_qprint($text)); 
        } 
        else 
        { 
          return iconv(&#39;gb2312&#39;,&#39;utf8&#39;,$text); 
        } 
      }  
      if($structure->type == 1) /* multipart */  
      {  
        while(list($index, $sub_structure) = each($structure->parts)) 
        {  
          if($part_number) 
          {  
            $prefix = $part_number . &#39;.&#39;;  
          }  
          $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[&#39;extension&#39;] = $extend[count($extend)-1]; 
          $file[&#39;pathname&#39;] = $this->setPathName($key, $file[&#39;extension&#39;]); 
          $file[&#39;title&#39;]   = !empty($name) ? htmlspecialchars($name) : str_replace(&#39;.&#39; . $file[&#39;extension&#39;], &#39;&#39;, $name); 
          $file[&#39;size&#39;]   = $struckture->parts[$key]->dparameters[1]->value; 
//         $file[&#39;tmpname&#39;]  = $struckture->parts[$key]->dparameters[0]->value; 
          if(@$struckture->parts[$key]->disposition=="ATTACHMENT") 
          { 
            $file[&#39;type&#39;]   = 1;    
          } 
          else 
          { 
            $file[&#39;type&#39;]   = 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[&#39;pathname&#39;],"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[&#39;extension&#39;] = $extend[count($extend)-1]; 
              $file[&#39;pathname&#39;] = $this->setPathName($key, $file[&#39;extension&#39;]); 
              $file[&#39;title&#39;]   = !empty($name) ? htmlspecialchars($name) : str_replace(&#39;.&#39; . $file[&#39;extension&#39;], &#39;&#39;, $name); 
              $file[&#39;size&#39;]   = $struckture->parts[$key]->parts[$keyb]->dparameters[1]->value; 
//             $file[&#39;tmpname&#39;]  = $struckture->parts[$key]->dparameters[0]->value; 
              $file[&#39;type&#39;]   = 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[&#39;pathname&#39;],"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(&#39;/<img .*? alt="PHP receiveMail实现收邮件功能" >/&#39;, $body, $matches); 
    if (!isset($matches[0])) return; 
     
    foreach ($matches[0] as $img) 
    { 
      // replace image web path with local path 
      preg_match(&#39;/src="(.*?)"/&#39;, $img, $m); 
      if (!isset($m[1])) continue; 
      $arr = parse_url($m[1]); 
      if (!isset($arr[&#39;scheme&#39;]) || !isset($arr[&#39;path&#39;]))continue; 
       
//     if (!isset($arr[&#39;host&#39;]) || !isset($arr[&#39;path&#39;]))continue; 
      if ($arr[&#39;scheme&#39;]!="http") 
      { 
        $filename=explode("@", $arr[&#39;path&#39;]); 
        $body = str_replace($img, &#39;<img alt="" src="&#39;.$path.$imageList[$filename[0]].&#39;"   style="max-width:90%" />&#39;, $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,&#39;utf8&#39;,$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(&#39;Ym/dHis&#39;, time()) . $fileID . mt_rand(0, 10000) . &#39;.&#39; . $extension; 
  } 
   
} 
?>
登录后复制

3.控制层./mailreceived/mailControl.php

./mailreceived/mailControl.php 内容如下:

<? 
/* 
 * File: mailControl.php 
 * Description: Received Mail Example 
 * Created: 03-06-2015 
 * Author: Sara Zhou 
 */ 
@header(&#39;Content-type: text/html;charset=UTF-8&#39;); 
error_reporting(0); 
ignore_user_abort(); // run script in background 
set_time_limit(0); // run script forever 
date_default_timezone_set(&#39;Asia/Shanghai&#39;); 
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 = &#39;&#39;; 
  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[&#39;type&#39;] == 0) 
          { 
            $imageList[$file[&#39;title&#39;]]=$file[&#39;pathname&#39;]; 
          } 
        } 
        $body = $obj->getBody($i,$this->webPath,$imageList); 
         
        $res[&#39;mail&#39;][]=array(&#39;head&#39;=>$head,&#39;body&#39;=>$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(&#39;Ym/&#39;, $this->now); 
    if(!file_exists($savePath)) 
    { 
      @mkdir($savePath, 0777, true); 
      touch($savePath . &#39;index.html&#39;); 
    } 
    $this->savePath = dirname($savePath) . &#39;/&#39;; 
  } 
    
} 
  $obj=new mailControl(); 
  //收取邮件 
  $res=$obj->mailReceived(); 
  echo "<pre class="brush:php;toolbar:false">";print_r($res); 
   
  //创建邮箱 
// $obj->creatBox("readyBox"); 
?>
登录后复制

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

相关推荐:

使用 PHPMailer 配合 QQ邮箱 发送邮件

PHPMAILER实现PHP发邮件功能

以上就是PHP receiveMail实现收邮件功能的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号