学习注水-20161113-php-imap收取邮件知识点mark一下「待解一个已知的bug」

9 篇文章 0 订阅
4 篇文章 0 订阅

PHP使用IMAP收取邮件

  • imap_append: 附加字符串到指定的邮箱中。
  • imap_base64: 解 BASE64 编码。
  • imap_body: 读信的内文。
  • imap_check: 返回邮箱信息。
  • imap_close: 关闭 IMAP 链接。
  • imap_createmailbox: 建立新的信箱。
  • imap_delete: 标记欲删除邮件。
  • imap_deletemailbox: 删除既有信箱。
  • imap_expunge: 删除已标记的邮件。
  • imap_fetchbody: 从信件内文取出指定部分。
  • imap_fetchstructure: 获取某信件的结构信息。
  • imap_header: 获取某信件的标头信息。
  • imap_headers: 获取全部信件的标头信息。
  • imap_listmailbox: 获取邮箱列示。
  • imap_listsubscribed: 获取订阅邮箱列示。
  • imap_mail_copy: 复制指定信件到它处邮箱。
  • imap_mail_move: 移动指定信件到它处邮箱。
  • imap_num_msg: 取得信件数。
  • imap_open: 打开 IMAP 链接。
  • imap_ping: 检查 IMAP 是否连接。
  • imap_renamemailbox: 更改邮箱名字。
  • imap_reopen: 重开 IMAP 链接。
  • imap_undelete: 取消删除邮件标记。
  • imap_8bit: 将八位转成 qp 编码。
  • imap_scanmailbox: 寻找信件有无特定字符串
  • imap_mailboxmsginfo: 取得目前邮箱的信息
  • imap_rfc822_write_address: 电子邮件位址标准化。
  • imap_rfc822_parse_adrlist: 解析电子邮件位址。
  • imap_setflag_full: 配置信件标志。
  • imap_clearflag_full: 清除信件标志。
  • imap_sort: 将信件标头排序。
  • imap_fetchheader: 取得原始标头。
  • imap_uid: 取得信件 UID。
  • imap_getmailboxes: 取得全部信件详细信息。
  • imap_getsubscribed: 列出所有订阅邮箱。
  • imap_msgno: 列出 UID 的连续信件。
  • imap_search: 搜寻指定标准的信件。
  • imap_last_error: 最后的错误信息。
  • imap_errors: 所有的错误信息。
  • imap_alerts: 所有的警告信息。
  • imap_status: 目前的状态信息。

IMAP 电子邮件系统函数库

PHP收邮件receiveMail

  • 必须开启imap扩展模块的支持
  • 此方法支持中文,不会乱码

第二个答案不错!
php imap收邮件乱码

我就想说,我管那么多做什么–,我就是想知道sent文件夹是哪一个罢了嘛。。

IMAP协议学习

有一个已知的bug,暂时不想解:对于纯文本的邮件无法正常解析,解决方法很简单,就是根据structure的type字段识别并对应if-else就可以了。

参考如下:
http://php.net/manual/en/function.imap-fetchbody.php

With an email message that only has a text body and does not have any mime attachments, imap-fetchbody() will return the following for each requested part number:
    (empty) - Entire message
    0 - Message header
    1 - Body text
With an email message that is a multi-part message in MIME format, and contains the message text in plain text and HTML, and has a file.ext attachment, imap-fetchbody() will return something like the following for each requested part number:
    (empty) - Entire message
    0 - Message header
    1 - MULTIPART/ALTERNATIVE
    1.1 - TEXT/PLAIN
    1.2 - TEXT/HTML
    2 - file.ext
Now if you attach the above email to an email with the message text in plain text and HTML, imap_fetchbody() will use this type of part number system:
    (empty) - Entire message
    0 - Message header
    1 - MULTIPART/ALTERNATIVE
    1.1 - TEXT/PLAIN
    1.2 - TEXT/HTML
    2 - MESSAGE/RFC822 (entire attached message)
    2.0 - Attached message header
    2.1 - TEXT/PLAIN
    2.2 - TEXT/HTML
    2.3 - file.ext

下附代码:

<?php
    define('DEBUG', true);
    header("Content-Type:text/html; charset=utf-8");

    //sent - 发件箱
    // $host = '{imap.163.com:993/ssl}INBOX';//&XfJT0ZAB-
    // $user = "xxx@163.com";
    // $password = "xxx";

    $host = '{imap.mxhichina.com:993/ssl}';//&XfJT0ZAB-
    $user = "xxx";
    $password = "xxx";

    // 定位到具体某一个文件夹
    // &XfJT0ZAB - sent
    // $mailboxes = imap_list($mbox, $host, '*');
    // $mailboxes = str_replace($host, '', $mailboxes);
    // var_dump($mailboxes);
    // $list = imap_mailboxmsginfo($mbox);
    // var_dump($list);
    $sent = "&XfJT0ZAB-";

    // 登陆连接 ssl imap
    $mbox = imap_open ($host, $user, $password, OP_HALFOPEN)
         or die("can't connect: " . imap_last_error());

    // 打开 sent - 发送箱文件夹
    imap_reopen($mbox, $host.$sent); 
    $emails = imap_search($mbox,'ALL'); 
    var_dump($emails);



    $email_total_array = array();
    if($emails) {
        $output = '';
        rsort($emails);
        //遍历所有邮件
        foreach($emails as $email_number) {

            // 控制循环次数
            // $ri++;
            // if($ri>6){
            //     break;
            // }

            //得到structure
            $email_array = array();

            // http://www.kuqin.com/php5_doc/function.imap-fetchstructure.html
            // type Primary body type
                // 0: text 
                // 1: multipart
                // 2: message
                // 3: application
                // 4: audio
                // 5: image
                // 6: video
                // 7: other
                    //header("Content-typee: ".$type); 
                    //header("Content-Disposition: attachment; filename=".$name); 
            // encoding    Body transfer encoding
            // ifsubtype   TRUE if there is a subtype string
            // subtype MIME subtype
            // ifdescription   TRUE if there is a description string
            // description Content description string
            // ifid    TRUE if there is an identification string
            // id  Identification string
            // lines   Number of lines
            // bytes   Number of bytes
            // ifdisposition   TRUE if there is a disposition string
            // disposition Disposition string
            // ifdparameters   TRUE if the dparameters array exists
            // dparameters An array of objects where each object has an "attribute" and a "value" property corresponding to the parameters on the Content-disposition MIMEheader.
            // ifparameters    TRUE if the parameters array exists
            // parameters  An array of objects where each object has an "attribute" and a "value" property.
            // parts   An array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part.
            $structure = imap_fetchstructure($mbox, $email_number);
            $message = "";
            $tt = 0; // 已知为 html/message
            //得到message
            if(isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
                $part = $structure->parts[1];

                // http://www.kuqin.com/php5_doc/function.imap-fetchbody.html
                // 0 - Message header
                // 1 - MULTIPART/ALTERNATIVE
                // 1.1 - TEXT/PLAIN
                // 1.2 - TEXT/HTML
                // 2 - MESSAGE/RFC822 (entire attached message)
                // 2.0 - Attached message header
                // 2.1 - TEXT/PLAIN
                // 2.2 - TEXT/HTML
                // 2.3 - file.ext

                // http://php.net/manual/en/function.imap-fetchbody.php
                // With an email message that only has a text body and does not have any mime attachments, imap-fetchbody() will return the following for each requested part number:
                // (empty) - Entire message
                // 0 - Message header
                // 1 - Body text

                // With an email message that is a multi-part message in MIME format, and contains the message text in plain text and HTML, and has a file.ext attachment, imap-fetchbody() will return something like the following for each requested part number:
                // (empty) - Entire message
                // 0 - Message header
                // 1 - MULTIPART/ALTERNATIVE
                // 1.1 - TEXT/PLAIN
                // 1.2 - TEXT/HTML
                // 2 - file.ext

                // Now if you attach the above email to an email with the message text in plain text and HTML, imap_fetchbody() will use this type of part number system:
                // (empty) - Entire message
                // 0 - Message header
                // 1 - MULTIPART/ALTERNATIVE
                // 1.1 - TEXT/PLAIN
                // 1.2 - TEXT/HTML
                // 2 - MESSAGE/RFC822 (entire attached message)
                // 2.0 - Attached message header
                // 2.1 - TEXT/PLAIN
                // 2.2 - TEXT/HTML
                // 2.3 - file.ext
                $message = imap_fetchbody($mbox, $email_number, 1.2);
                if($message == ""){
                    $message = imap_fetchbody($mbox, $email_number, 2);
                }else{
                    $tt = 1; // 不是 html/message
                }
                $coding = $part->encoding;
                if($tt == 0){ // 已知为 html/message

                    // http://www.kuqin.com/php5_doc/function.imap-fetchstructure.html
                    // 0   7BIT
                    // 1   8BIT
                    // 2   BINARY
                    // 3   BASE64
                    // 4   QUOTED-PRINTABLE
                    // 5   OTHER
                    if ($coding == 0)
                    {
                        $message = $message;
                    }
                    elseif ($coding == 1)
                    {
                        $message = $message;
                    }
                    elseif ($coding == 2)
                    {
                        $message = $message;
                    }
                    elseif ($coding == 3)
                    {
                        $message = imap_base64($message);
                    }
                    elseif ($coding == 4)
                    {
                        $message = imap_qprint($message);
                    }
                    elseif ($coding == 5)
                    {
                        $message = $message;
                    } 
                }
                //echo "<br>^^<br>".$message."<br/>$$<br>";
                //echo "<img src=".$message.">";
            }

            //得到邮件的标头部分:是否已读,发件人,日期,标题。

            // http://www.kuqin.com/php5_doc/function.imap-headerinfo.html
            // to[]
               // personal
               // adl
               // mailbox
               // host
            // from[]
               // personal
               // adl
               // mailbox
               // host
            // cc[]
               // personal
               // adl
               // mailbox
               // host
            // bcc[]
               // personal
               // adl
               // mailbox
               // host
            // reply_to[]
               // personal
               // adl
               // mailbox
               // host
            // sender[]
               // personal
               // adl
               // mailbox
               // host
            // return_path[]
               // personal
               // adl
               // mailbox
               // host
            // udate (mail message date in unix time)
            // fetchfrom (from line formatted to fit fromlength characters)
            // fetchsubject (subject line formatted to fit subjectlength characters)
            $header = imap_headerinfo($mbox, $email_number);
            $fromaddr = $header->from[0]->mailbox . "@" . $header->from[0]->host;
            echo $fromaddr."##<br>";

            // http://www.baike.com/wiki/imap_fetch_overview
            // subject - the messages subject 
            // from - who sent it 
            // to - recipient 
            // date - when was it sent 
            // message_id - Message-ID 
            // references - is a reference to this message id 
            // in_reply_to - is a reply to this message id 
            // size - size in bytes 
            // uid - UID the message has in the mailbox 
            // msgno - message sequence number in the mailbox 
            // recent - this message is flagged as recent 
            // flagged - this message is flagged 
            // answered - this message is flagged as answered 
            // deleted - this message is flagged for deletion 
            // seen - this message is flagged as already read 
            // draft - this message is flagged as being a draft 
            $overview = imap_fetch_overview($mbox, $email_number, 0);

            // http://www.php100.com/cover/php/1034.html
            // imap_utf8 — Converts MIME-encoded text to UTF-8
            $sender = imap_utf8($overview[0]->from);
            $seen = $overview[0]->seen ? 'read' : 'unread';
            $date = $overview[0]->date;
            $subject = imap_utf8($overview[0]->subject);
            $SendEmailAddress = $fromaddr;

            echo $sender."**<br/>";
            //得到message的字符编码。
            if($tt == 0){ // 已知为 html/message

                // http://www.jb51.net/article/27282.htm
                // 使用 mb_detect_encoding 函数进行编码识别
                $encodedd = mb_detect_encoding($message, array('UTF-8','US-ASCII','GB2312', 'ISO-8859-1','ISO-8859-2','ISO-8859-4','ISO-8859-5','ISO-8859-6','ISO-8859-7','ISO-8859-8','ISO-8859-9','ISO-8859-10','ISO-2022-JP','ISO-2022-KR'));

                //进行转码
                // http://www.jb51.net/article/14530.htm
                // iconv函数库能够完成各种字符集间的转换
                if($encodedd == "EUC-CN"){
                    $message= iconv("GB2312", "UTF-8", $message);
                }else if($encodedd == "ISO-8859-1"){
                    $message= iconv("ISO-8859-1", "UTF-8", $message);
                }else if($encodedd == "ISO-8859-2"){
                    $message= iconv("ISO-8859-2", "UTF-8", $message);
                }else if($encodedd == "ISO-8859-4"){
                    $message= iconv("ISO-8859-4", "UTF-8", $message);
                }else if($encodedd == "ISO-8859-5"){
                    $message= iconv("ISO-8859-5", "UTF-8", $message);
                }else if($encodedd == "ISO-8859-6"){
                    $message= iconv("ISO-8859-6", "UTF-8", $message);
                }else if($encodedd == "ISO-8859-7"){
                    $message= iconv("ISO-8859-7", "UTF-8", $message);
                }else if($encodedd == "ISO-8859-8"){
                    $message= iconv("ISO-8859-8", "UTF-8", $message);
                }else if($encodedd == "ISO-8859-9"){
                    $message= iconv("ISO-8859-9", "UTF-8", $message);
                }else if($encodedd == "ISO-8859-10"){
                    $message= iconv("ISO-8859-10", "UTF-8", $message);
                }else if($encodedd == "ISO-2022-JP"){
                    $message= iconv("ISO-2022-JP", "UTF-8", $message);
                }else if($encodedd == "ISO-2022-KR"){
                    $message= iconv("ISO-2022-KR", "UTF-8", $message);
                }else{
                    $message= $message;
                }
                // 让我们一起来解一个编码的 bug !!! 并且 mark 一个转多种编码的在线平台网址:http://bianma.911cha.com/
                if($message == base64_encode(base64_decode($message))){//base64........日
                    $message = base64_decode($message);
                }    
            }
            else{ // 不是 html/message
                $message= $message;
            }

            //邮箱信息保存到数组
            //加载附件
            // $attachments = array();
            /* if any attachments found... */
            // 这段我不关心 ==。。
            // if(isset($structure->parts) && count($structure->parts)) {
            //     for($i = 0; $i < count($structure->parts); $i++) {
            //         $attachments[$i] = array(
            //             'is_attachment' => false,
            //             'filename' => '',
            //             'name' => '',
            //             'attachment' => ''
            //         );

            //         if($structure->parts[$i]->ifdparameters) {
            //             foreach($structure->parts[$i]->dparameters as $object) {
            //                 if(strtolower($object->attribute) == 'filename') {
            //                     $attachments[$i]['is_attachment'] = true;
            //                     $attachments[$i]['filename'] = imap_utf8($object->value);
            //                 }
            //             }
            //         }

            //         if($structure->parts[$i]->ifparameters) {
            //             foreach($structure->parts[$i]->parameters as $object) 
            //             {
            //                 if(strtolower($object->attribute) == 'name') 
            //                 {
            //                     $attachments[$i]['is_attachment'] = true;
            //                     $attachments[$i]['name'] = imap_utf8($object->value);
            //                 }
            //             }
            //         }

            //         if($attachments[$i]['is_attachment']) {
            //             $attachments[$i]['attachment'] = imap_fetchbody($mbox, $email_number, $i+1);

            //             /* 4 = QUOTED-PRINTABLE encoding */
            //             if($structure->parts[$i]->encoding == 3) { 
            //                 $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
            //             }
            //             /* 3 = BASE64 encoding */
            //             elseif($structure->parts[$i]->encoding == 4) { 
            //                 $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
            //             }
            //         }
            //     }
            // }

            /* iterate through each attachment and save it */
            // $atta_array = array();
            // foreach($attachments as $attachment) {
            //     if($attachment['is_attachment'] == 1) {
            //         $filename = $attachment['name'];
            //         if(empty($filename))
            //             $filename = $attachment['filename'] . "_" . time() . ".dat";

            //         /* prefix the email number to the filename in case two emails
            //         * have the attachment with the same file name.
            //         */
            //         $l_filename = $filename;
            //         $file_hz = strrev(substr(strrev($filename),0,4));
            //         $datatimes = date('Y-m-d-G-i-s', time());
            //         //$datatimes = str_replace(" ","-",$datatimes);
            //         $datatimes = $email_number."-".$datatimes;

            //         $filename =  $datatimes.$file_hz;
            //         $file_dir =  "file/".$filename;
            //         $atta_array[] = array("filename"=>$filename,"filealiases"=>$l_filename,"filedir"=>$file_dir);
            //         //win 7下面的文件编码都是gb2312,所以需要转换编码。
            //         // $filename = iconv("UTF-8", "GB2312",$filename);
            //         //echo $l_filename;  
            //         $fp = fopen("./".$file_dir, "w+");
            //         fwrite($fp, $attachment['attachment']);
            //         fclose($fp);
            //     }
            // }
            //var_dump($atta_array);
            加载附件代码结束。

            $email_total_array[] = array("attament"=>$atta_array ,"email_number"=>$email_number,"seen"=>$seen,"date"=>$date,"sender"=>$sender,"subject"=>$subject,"message"=>$message,"SendEmailAddress"=>$SendEmailAddress);
            //$email_total_array['attament'] = $atta_array;
        }


        //把信息写入到数据库中
        // 这段我也不关心--看上去是 APP 的东西,原作者真是==大神
        // $app = Mage::app();
        // foreach($email_total_array as $ea){
        //     $n_sender = $ea['sender'];
        //     if(strstr($n_sender," <")){
        //         $e_sender = substr($n_sender,0,strpos($n_sender," <"));
        //     }else{
        //         $e_sender = $n_sender;
        //     }
        //     $email_list = Mage::getModel("email/list");
        //     $email_list->setEmailMessageNo($ea['email_number']);
        //     $email_list->setSendEmailAddress($ea['SendEmailAddress']);
        //     $email_list->setEmailSender($e_sender);
        //     $email_list->setReceiveEmailAddress($user);
        //     $email_list->setEmailSendTime($ea['date']);
        //     $email_list->setEmailTitle($ea['subject']);
        //     $email_list->setEmailContent($ea['message']);
        //     $email_list->setOrderNo();
        //     $email_list->setCustomerService();
        //     $email_list->setOrderStyle();
        //     $email_list->setLanguage();
        //     $email_list->setOrderTotal();
        //     $email_list->setCaseStatus();
        //     $email_list->save();
        //     $email_id = $email_list->getId();//
        //     $attament = $ea['attament'];
        //     foreach($attament as $aa){
        //         $filename = $aa['filename'];//
        //         $filealiases = $aa['filealiases'];//
        //         $filedir = $aa['filedir'];//
        //         //保存
        //         $email_attachment = Mage::getModel("email/attachment");
        //         $email_attachment->setEmailId($email_id);
        //         $email_attachment->setAttachmentName($filename);
        //         $email_attachment->setAttachmentAliases($filealiases);
        //         $email_attachment->setAttachmentDir($filedir);
        //         $email_attachment->save();
        //     }
        // }

    }

    imap_close($mbox);

?>

参考:

「重要,提供了重要思路!」

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值