php专区

 首页 > php专区 > PHP应用 > 常用功能 > PHP邮件接收与发送类实现程序详解 - php高级应用

PHP邮件接收与发送类实现程序详解 - php高级应用

分享到:
【字体:
导读:
          我想使用邮件接收类的朋友可能比较少,但是发送邮件的类使用的朋友比较多啊,下面我来分别给大家介绍PHP邮件接收与发送类实现程序详解,希望对...

PHP邮件接收与发送类实现程序详解

我想使用邮件接收类的朋友可能比较少,但是发送邮件的类使用的朋友比较多啊,下面我来分别给大家介绍PHP邮件接收与发送类实现程序详解,希望对大家所有帮助哦。

主要的改进如下:

1、新增了listMessages方法,用于列表邮件列表,且带有分页功能,更加方便调用:

  1. /** 
  2.  * listMessages - 获取邮件列表 
  3.  * @param $page - 第几页 
  4.  * @param $per_page - 每页显示多少封邮件 
  5.  * @param $sort - 邮件排序,如:array('by' => 'date', 'direction' => 'desc') 
  6.  * */ 
  7. function listMessages($page = 1, $per_page = 25, $sort = null){} 

2、新增了两个编码转换的方法,主要用于对邮件的相关信息进行编码转换,调用方法如下:

  1. include("receivemail.class.php"); 
  2. $obj = receiveMail('abc@abc.com','xxxxxx','abc@abc.com','pop.abc.com','pop3','110', false); 
  3. $obj->connect(); 
  4. $maillist = $obj->listMessages(); 
  5. print_r($maillist); 
  6. 运行结果大致如下: 
  7. Array 
  8.     [res] => Array 
  9.         ( 
  10.          [0] => stdClass Object 
  11.           ( 
  12.            [subject] => 解决PHP邮件接收类的乱码问题 
  13.            [from] => xxx  
  14.            [to] => abc  
  15.            [date] => Mon, 28 Jan 2013 14:23:06 +0800 (CST) 
  16.            [message_id] => <2afc51061915f95-00004.Richmail.00037000523146269922@xxx.com> 
  17.                     [size] => 42259 
  18.                     [uid] => 1 
  19.                     [msgno] => 1 
  20.                     [recent] => 1 
  21.                     [flagged] => 0 
  22.                     [answered] => 0 
  23.                     [deleted] => 0 
  24.                     [seen] => 0 
  25.                     [draft] => 0 
  26.                     [body] => 邮件内容 
  27.           ) 
  28.         ) 
  29.  [start] => 1 
  30.     [limit] => 25 
  31.     [sorting] => Array 
  32.         ( 
  33.             [by] =>  
  34.             [direction] =>  
  35.         ) 
  36.     [total] => 47 
  37.     [pages] => 2 

receivemail.class.php类文件,代码如下:

  1. class receiveMail 
  2.  var $server=''
  3.  var $username=''
  4.  var $password=''
  5.  
  6.  var $marubox='';      
  7.  
  8.  var $email='';    
  9.  
  10.  function receiveMail($username,$password,$EmailAddress,$mailserver='localhost',$servertype='pop',$port='110',$ssl = false) //Constructure 
  11.  { 
  12.   if($servertype=='imap'
  13.   { 
  14.    if($port==''$port='143';  
  15.    $strConnect='{'.$mailserver.':'.$port'}INBOX';  
  16.   } 
  17.   else 
  18.   { 
  19.    $strConnect='{'.$mailserver.':'.$port'/pop3'.($ssl ? "/ssl" : "").'}INBOX';  
  20.   } 
  21.   $this->server   = $strConnect
  22.   $this->username   = $username
  23.   $this->password   = $password
  24.   $this->email   = $EmailAddress
  25.  } 
  26.  
  27.  function connect() //Connect To the Mail Box 
  28.  { 
  29.   $this->marubox=@imap_open($this->server,$this->username,$this->password); 
  30.    
  31.   if(!$this->marubox) 
  32.   { 
  33.    echo "Error: Connecting to mail server"
  34.    exit
  35.   } 
  36.  } 
  37.  
  38.  function listMessages($page = 1, $per_page = 25, $sort = null)  
  39.   { 
  40.        $limit = ($per_page * $page); 
  41.        $start = ($limit - $per_page) + 1; 
  42.        $start = ($start < 1) ? 1 : $start
  43.        $limit = (($limit - $start) != ($per_page-1)) ? ($start + ($per_page-1)) : $limit
  44.        $info = imap_check($this->marubox); 
  45.        $limit = ($info->Nmsgs < $limit) ? $info->Nmsgs : $limit
  46.  
  47.        if(true === is_array($sort))  
  48.        { 
  49.            $sorting = array
  50.                'direction' => array'asc' => 0, 'desc' => 1), 
  51.                'by'        => array('date' => SORTDATE, 'arrival' => SORTARRIVAL, 
  52.                                    'from' => SORTFROM, 'subject' => SORTSUBJECT, 'size' => SORTSIZE)); 
  53.            $by = (true === is_int($by = $sorting['by'][$sort[0]])) ? $by : $sorting['by']['date']; 
  54.            $direction = (true === is_int($direction = $sorting['direction'][$sort[1]])) ? $direction : $sorting['direction']['desc']; 
  55.            $sorted = imap_sort($this->marubox, $by$direction); 
  56.            $msgs = array_chunk($sorted$per_page); 
  57.            $msgs = $msgs[$page-1]; 
  58.        } 
  59.        else  
  60.        { 
  61.            $msgs = range($start$limit); //just to keep it consistent 
  62.        } 
  63.        $result = imap_fetch_overview($this->marubox, implode($msgs','), 0); 
  64.        if(false === is_array($result)) return false; 
  65.  
  66.        foreach ($result as $k => $r
  67.        { 
  68.          $result[$k]->subject = $this->_imap_utf8($r->subject); 
  69.          $result[$k]->from = $this->_imap_utf8($r->from); 
  70.          $result[$k]->to = $this->_imap_utf8($r->to); 
  71.    $result[$k]->body = $this->getBody($r->msgno); 
  72.        } 
  73.        //sorting! 
  74.        if(true === is_array($sorted))  
  75.        { 
  76.            $tmp_result = array(); 
  77.            foreach($result as $r
  78.            { 
  79.              $tmp_result[$r->msgno] = $r
  80.            } 
  81.  
  82.            $result = array(); 
  83.            foreach($msgs as $msgno)  
  84.            { 
  85.     $result[] = $tmp_result[$msgno]; 
  86.            } 
  87.        } 
  88.  
  89.        $return = array('res' => $result
  90.                        'start' => $start
  91.                        'limit' => $limit
  92.                        'sorting' => array('by' => $sort[0], 'direction' => $sort[1]), 
  93.                        'total' => imap_num_msg($this->marubox)); 
  94.        $return['pages'] = ceil($return['total'] / $per_page); 
  95.        return $return
  96.    } 
  97.  
  98.  function getHeaders($mid// Get Header info 
  99.  { 
  100.   if(!$this->marubox) 
  101.    return false; 
  102.   $mail_header=imap_header($this->marubox,$mid); 
  103.   $sender=$mail_header->from[0]; 
  104.   $sender_replyto=$mail_header->reply_to[0]; 
  105.   if(strtolower($sender->mailbox)!='mailer-daemon' && strtolower($sender->mailbox)!='postmaster'
  106.   { 
  107.    $mail_details=array
  108.      'from'=>strtolower($sender->mailbox).'@'.$sender->host, 
  109.      'fromName'=>$sender->personal, 
  110.      'toOth'=>strtolower($sender_replyto->mailbox).'@'.$sender_replyto->host, 
  111.      'toNameOth'=>$sender_replyto->personal, 
  112.      'subject'=>$mail_header->subject, 
  113.      'to'=>strtolower($mail_header->toaddress) 
  114.     ); 
  115.   } 
  116.   return $mail_details
  117.  } 
  118.  
  119.  function get_mime_type(&$structure//Get Mime type Internal Private Use 
  120.  {  
  121.   $primary_mime_type = array("TEXT""MULTIPART""MESSAGE""APPLICATION""AUDIO""IMAGE""VIDEO""OTHER");  
  122.    
  123.   if($structure->subtype) {  
  124.    return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype;  
  125.   }  
  126.   return "TEXT/PLAIN";  
  127.  }  
  128.  
  129.  function get_part($stream$msg_number$mime_type$structure = false, $part_number = false) //Get Part Of Message Internal Private Use 
  130.  {  
  131.   if(!$structure) {  
  132.    $structure = imap_fetchstructure($stream$msg_number);  
  133.   }  
  134.   if($structure) {  
  135.    if($mime_type == $this->get_mime_type($structure)) 
  136.    {  
  137.     if(!$part_number)  
  138.     {  
  139.      $part_number = "1";  
  140.     }  
  141.     $text = imap_fetchbody($stream$msg_number$part_number);  
  142.     if($structure->encoding == 3)  
  143.     {  
  144.      return imap_base64($text);  
  145.     }  
  146.     else if($structure->encoding == 4)  
  147.     {  
  148.      return imap_qprint($text);  
  149.     }  
  150.     else 
  151.     {  
  152.      return $text;  
  153.     }  
  154.    }  
  155.    if($structure->type == 1) /* multipart */  
  156.    {  
  157.     while(list($index$sub_structure) = each($structure->parts)) 
  158.     {  
  159.      if($part_number
  160.      {  
  161.       $prefix = $part_number . '.';  
  162.      }  
  163.      $data = $this->get_part($stream$msg_number$mime_type$sub_structure$prefix . ($index + 1));  
  164.      if($data
  165.      {  
  166.       return $data;  
  167.      }  
  168.     }  
  169.    }  
  170.   }  
  171.   return false;  
  172.  }  
  173.  
  174.  function getTotalMails() //Get Total Number off Unread Email In Mailbox 
  175.  { 
  176.   if(!$this->marubox) 
  177.    return false; 
  178.   $headers=imap_headers($this->marubox); 
  179.   return count($headers); 
  180.  } 
  181.  function GetAttach($mid,$path// Get Atteced File from Mail 
  182.  { 
  183.   if(!$this->marubox) 
  184.   { 
  185.    return false; 
  186.   } 
  187.   $struckture = imap_fetchstructure($this->marubox,$mid); 
  188.   $ar=""
  189.   if($struckture->parts) 
  190.         { 
  191.    foreach($struckture->parts as $key => $value
  192.    { 
  193.     $enc=$struckture->parts[$key]->encoding; 
  194.     if($struckture->parts[$key]->ifdparameters) 
  195.     { 
  196.      $name=$struckture->parts[$key]->dparameters[0]->value; 
  197.      $message = imap_fetchbody($this->marubox,$mid,$key+1); 
  198.      switch ($enc
  199.      { 
  200.       case 0: 
  201.        $message = imap_8bit($message); 
  202.        break
  203.       case 1: 
  204.        $message = imap_8bit ($message); 
  205.        break
  206.       case 2: 
  207.        $message = imap_binary ($message); 
  208.        break
  209.       case 3: 
  210.        $message = imap_base64 ($message);  
  211.        break
  212.       case 4: 
  213.        $message = quoted_printable_decode($message); 
  214.        break
  215.       case 5: 
  216.        $message = $message
  217.        break
  218.      } 
  219.      $fp=fopen($path.$name,"w"); 
  220.      fwrite($fp,$message); 
  221.      fclose($fp); 
  222.      $ar=$ar.$name.","
  223.     } 
  224.     // Support for embedded attachments starts here 
  225.     if($struckture->parts[$key]->parts) 
  226.     { 
  227.      foreach($struckture->parts[$key]->parts as $keyb => $valueb
  228.      { 
  229.       $enc=$struckture->parts[$key]->parts[$keyb]->encoding; 
  230.       if($struckture->parts[$key]->parts[$keyb]->ifdparameters) 
  231.       { 
  232.        $name=$struckture->parts[$key]->parts[$keyb]->dparameters[0]->value; 
  233.        $partnro = ($key+1).".".($keyb+1); 
  234.        $message = imap_fetchbody($this->marubox,$mid,$partnro); 
  235.        switch ($enc
  236.        { 
  237.         case 0: 
  238.            $message = imap_8bit($message); 
  239.          break
  240.         case 1: 
  241.            $message = imap_8bit ($message); 
  242.          break
  243.         case 2: 
  244.            $message = imap_binary ($message); 
  245.          break
  246.         case 3: 
  247.            $message = imap_base64 ($message); 
  248.          break
  249.         case 4: 
  250.            $message = quoted_printable_decode($message); 
  251.          break
  252.         case 5: 
  253.            $message = $message
  254.          break
  255.        } 
  256.        $fp=fopen($path.$name,"w"); 
  257.        fwrite($fp,$message); 
  258.        fclose($fp); 
  259.        $ar=$ar.$name.","
  260.       } 
  261.      } 
  262.     }     
  263.    } 
  264.   } 
  265.   $ar=substr($ar,0,(strlen($ar)-1)); 
  266.   return $ar
  267.  } 
  268.  
  269.  function getBody($mid// Get Message Body 
  270.  { 
  271.   if(!$this->marubox) 
  272.   { 
  273.    return false; 
  274.   } 
  275.   $body = $this->get_part($this->marubox, $mid"TEXT/HTML"); 
  276.   if ($body == ""
  277.   { 
  278.    $body = $this->get_part($this->marubox, $mid"TEXT/PLAIN"); 
  279.   } 
  280.   if ($body == "")  
  281.   { 
  282.    return ""
  283.   } 
  284.   return $this->_iconv_utf8($body); 
  285.  } 
  286.  
  287.  function deleteMails($mid// Delete That Mail 
  288.  { 
  289.   if(!$this->marubox) 
  290.    return false; 
  291.  
  292.   imap_delete($this->marubox,$mid); 
  293.  } 
  294.  
  295.  function close_mailbox() //Close Mail Box 
  296.  { 
  297.   if(!$this->marubox) 
  298.    return false; 
  299.   imap_close($this->marubox,CL_EXPUNGE); 
  300.  } 
  301.  
  302.  function _imap_utf8($text
  303.  { 
  304.   if(preg_match('/=?([a-zA-z0-9-]+)?(.*)?=/i'$text$match)) 
  305.   { 
  306.    $text = imap_utf8($text); 
  307.    if(strtolower(substr($match[1], 0, 2)) == 'gb'
  308.    { 
  309.     $text = iconv('gbk''utf-8'$text); 
  310.    } 
  311.    return $text
  312.   } 
  313.   return $this->_iconv_utf8($text); 
  314.  } 
  315.  
  316.  function _iconv_utf8($text
  317.  { 
  318.   $s1 = iconv('gbk''utf-8'$text); 
  319.   $s0 = iconv('utf-8''gbk'$s1); 
  320.   if($s0 == $text
  321.   { 
  322.    return $s1
  323.   } 
  324.   else 
  325.   { 
  326.    return $text
  327.   } 
  328.  } 

下面是一个php邮件发送的类的一个函数,代码如下:

  1. function sendmail($to$from$subject = ""$body = ""$mailtype$cc = ""$bcc = ""$additional_headers = ""
  2.     { 
  3.         $mail_from = $this->get_address($this->strip_comment($from)); 
  4.         $body = ereg_replace("(^|(rn))(.)""1.3"$body); 
  5.         $header = "MIME-Version:1.0rn"
  6.         if($mailtype=="HTML"){ 
  7.             $header .= "Content-Type:text/htmlrn"
  8.         } 
  9.         $header .= "To: ".$to."rn"
  10.         if ($cc != "") { 
  11.             $header .= "Cc: ".$cc."rn"
  12.         } 
  13.         $header .= "From: 报名邮件.<".$from.">rn"
  14.         $header .= "Subject: ".$subject."rn"
  15.         $header .= $additional_headers
  16.         $header .= "Date: ".date("r")."rn"
  17.         $header .= "X-Mailer:By Redhat (PHP/".phpversion().")rn"
  18.   $utfheader=iconv("UTF-8","GB2312",$header); 
  19.         list($msec$sec) = explode(" ", microtime()); 
  20.         $header .= "Message-ID: <".date("YmdHis"$sec).".".($msec*1000000).".".$mail_from.">rn"
  21.         $TO = explode(","$this->strip_comment($to)); 
  22.         if ($cc != "") { 
  23.             $TO = array_merge($TOexplode(","$this->strip_comment($cc))); 
  24.         } 
  25.         if ($bcc != "") { 
  26.             $TO = array_merge($TOexplode(","$this->strip_comment($bcc))); 
  27.         } 
  28.         $sent = TRUE; 
  29.         foreach ($TO as $rcpt_to) { 
  30.             $rcpt_to = $this->get_address($rcpt_to); 
  31.             if (!$this->smtp_sockopen($rcpt_to)) { 
  32.                 $this->log_write("Error: Cannot send email to ".$rcpt_to."n"); 
  33.                 $sent = FALSE; 
  34.                 continue
  35.             } 
  36.             if ($this->smtp_send($this->host_name, $mail_from$rcpt_to$utfheader$body)) { 
  37.                 $this->log_write("E-mail has been sent to <".$rcpt_to.">n"); 
  38.             } else { 
  39.                 $this->log_write("Error: Cannot send email to <".$rcpt_to.">n"); 
  40.                 $sent = FALSE; 
  41.             } 
  42.             fclose($this->sock); 
  43.             $this->log_write("Disconnected from remote hostn"); 
  44.         } 
  45.         return $sent
  46.     } 

我们如何调用这个类呢?示例代码如下:

  1. include("sendmail.php");//发送邮件类 
  2.  ####################--发邮件--#################### 
  3.  $smtpserver  =  "smtp.126.com";//SMTP服务器 
  4.  $smtpserverport = 25;//SMTP服务器端口 
  5.  $smtpusermail  =  "test@126.com";//SMTP服务器的用户邮箱 
  6.  $smtpuser   =  "test";//SMTP服务器的用户帐号 
  7.  $smtppass   =  "123456";//SMTP服务器的用户密码 
  8.  $smtpemailto  =  "dianzhong@126.com";//发送给谁 
  9.  $mailsubject  =  $username.'报名!';//邮件主题 
  10.  $mailtime  = date("Y-m-d H:i:s"); 
  11.  $mailbody   =  $content;//邮件内容 
  12.  $utfmailbody = iconv("UTF-8","GB2312",$mailbody);//转换邮件编码 
  13.  $mailtype   =  "HTML";//邮件格式(HTML/TXT),TXT为文本邮件 
在这里需要一个smtp服务器,我们可以注册一个126的邮箱, 在上面的代码中,修改成你自己注册的邮箱地址和用户名、密码即可。
分享到:
memcached启动和关闭的方法 - php高级应...
memcached启动和关闭的方法 memcached的启动与关闭方法很比较简单,下面我来介绍在linux系统中具体使用什么命令来启动或停止memcached吧,希望文章对各位会有所帮助。 1.启动memcached # /usr/local/bin/memcached -d -m 2048  -u root -l 192.168.1.20 -p 12111 -c 1024 -P /tmp/memcach...
PHP利用Jmail组件实现发送邮件 - php高级...
PHP利用Jmail组件实现发送邮件 学过asp的朋友可能知道jmail组件是使用在asp中一个常用的邮箱发送功能,在php中如果想调用jmail功能我们需要使用com组件来操作,我们先来介绍格式,代码如下: $Jmail = new com("Jmail.Message"); //实例化一个Jmail对象  $Jmail->SiLent=true; //设...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……