最模板 - 外贸网站建设,外贸网站模板

最模板

当前位置: 首页 > 建站教程 > php教程 >

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

时间:2014-06-09 16:40来源: 作者: 点击: 次
我想使用邮件接收类的朋友可能比较少,但是发送邮件的类使用的朋友比较多啊,下面我来分别给大家介绍PHP邮件接收与发送类实现程序详解,希望对大家所有帮助哦。 主要的改进如下: 1、新增

我想使用邮件接收类的朋友可能比较少,但是发送邮件的类使用的朋友比较多啊,下面我来分别给大家介绍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. ( 
  9.     [res] => Array 
  10.         ( 
  11.          [0] => stdClass Object 
  12.           ( 
  13.            [subject] => 解决PHP邮件接收类的乱码问题 
  14.            [from] => xxx <xxx@phper.org.cn> 
  15.            [to] => abc <abc@abc.com> 
  16.            [date] => Mon, 28 Jan 2013 14:23:06 +0800 (CST) 
  17.            [message_id] => <2afc51061915f95-00004.Richmail.00037000523146269922@xxx.com> 
  18.                     [size] => 42259 
  19.                     [uid] => 1 
  20.                     [msgno] => 1 
  21.                     [recent] => 1 
  22.                     [flagged] => 0 
  23.                     [answered] => 0 
  24.                     [deleted] => 0 
  25.                     [seen] => 0 
  26.                     [draft] => 0 
  27.                     [body] => 邮件内容 
  28.           ) 
  29.         ) 
  30.  [start] => 1 
  31.     [limit] => 25 
  32.     [sorting] => Array 
  33.         ( 
  34.             [by] =>  
  35.             [direction] =>  
  36.         ) 
  37.     [total] => 47 
  38.     [pages] => 2 
  39. ) 

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

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

下面是一个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($TO, explode(",", $this->strip_comment($cc))); 
  24.         } 
  25.         if ($bcc != "") { 
  26.             $TO = array_merge($TO, explode(",", $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的邮箱, 在上面的代码中,修改成你自己注册的邮箱地址和用户名、密码即可。 (责任编辑:admin)
------分隔线----------------------------
栏目列表
推荐内容