PHP获取邮件

<?php
@header('Content-type: text/html;charset=UTF-8');
ignore_user_abort(); // run script in background
set_time_limit(0); // run script forever
include("receivemail.class.php");
$fileSavePaht = DT_ROOT . '/api/pop/emailsave/';
$obj = new receiveMail('', '', '', 'imap.exmail.qq.com', 'imap', '143', false);
$obj->connect();
$tot = $obj->getTotalMails(); //Total Mails in Inbox Return integer value
echo "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)
    echo "Subjects :: " . $head['subject'] . "<br>";
    echo "TO :: " . $head['to'] . "<br>";
    echo "To Other :: " . $head['toOth'] . "<br>";
    echo "ToName Other :: " . $head['toNameOth'] . "<br>";
    echo "From :: " . $head['from'] . "<br>";
    echo "FromName :: " . $head['fromName'] . "<br>";
    echo "<br><br>";
    echo "<br>*******************************************************************************************<BR>";
    echo $obj->getBody($i);  // Get Body Of Mail number Return String Get Mail id in interger
    print_r("附件下载区");
    print_r("<br />");
    $str = $obj->GetAttach($i, $fileSavePaht); // Get attached File from Mail Return name of file in comma separated string  args. (mailid, Path to store file)
    $ar = explode(",", $str);
    foreach ($ar as $key => $value)
        echo ($value == "") ? "" : "Atteched File :: " . $value . "<br>";
    echo "<br>------------------------------------------------------------------------------------------<BR>";
    $obj->removeEamil($i); // Delete Mail from Mail box
}
$obj->close_mailbox();   //Close Mail Box
echo '执行完成!!!!!';
?>

<?php

class receiveMail {

    var $server = '';
    var $username = '';
    var $password = '';
    var $marubox = '';
    var $email = '';
    var $backUp = '{imap.qq.com}&UXZO1mWHTvZZOQ-/beifen';

    function receiveMail($username, $password, $EmailAddress, $mailserver = 'localhost', $servertype = 'pop', $port = '110', $ssl = false) { //Constructure
        if ($servertype == 'imap') {
            if ($port == '')
                $port = '143';

            //方案1
            $strConnect="{{$mailserver}:143}INBOX" ;
            //案列2 SSL
            //$strConnect = '{' . $mailserver . ':' . $port . '/imap/ssl}INBOX';
        }
        else {
            $strConnect = '{' . $mailserver . ':' . $port . '/pop3' . ($ssl ? "/ssl" : "") . '}INBOX';
        }
        $this->server = $strConnect;
        $this->username = $username;
        $this->password = $password;
        $this->email = $EmailAddress;
    }

    function connect() {
        $this->marubox = imap_open($this->server, $this->username, $this->password);
        if (!$this->marubox) {
            echo "Error: Connecting to mail server";
            exit;
        }
    }

    function listMessages($page = 1, $per_page = 25, $sort = null) {
        $limit = ($per_page * $page);
        $start = ($limit - $per_page) + 1;
        $start = ($start < 1) ? 1 : $start;
        $limit = (($limit - $start) != ($per_page - 1)) ? ($start + ($per_page - 1)) : $limit;
        $info = imap_check($this->marubox);
        $limit = ($info->Nmsgs < $limit) ? $info->Nmsgs : $limit;

        if (true === is_array($sort)) {
            $sorting = array(
                'direction' => array('asc' => 0, 'desc' => 1),
                'by' => array('date' => SORTDATE, 'arrival' => SORTARRIVAL,
                    'from' => SORTFROM, 'subject' => SORTSUBJECT, 'size' => SORTSIZE));
            $by = (true === is_int($by = $sorting['by'][$sort[0]])) ? $by : $sorting['by']['date'];
            $direction = (true === is_int($direction = $sorting['direction'][$sort[1]])) ? $direction : $sorting['direction']['desc'];
            $sorted = imap_sort($this->marubox, $by, $direction);
            $msgs = array_chunk($sorted, $per_page);
            $msgs = $msgs[$page - 1];
        } else {
            $msgs = range($start, $limit); //just to keep it consistent
        }
        $result = imap_fetch_overview($this->marubox, implode($msgs, ','), 0);
        if (false === is_array($result))
            return false;

        foreach ($result as $k => $r) {
            $result[$k]->subject = $this->_imap_utf8($r->subject);
            $result[$k]->from = $this->_imap_utf8($r->from);
            $result[$k]->to = $this->_imap_utf8($r->to);
            $result[$k]->body = $this->getBody($r->msgno);
        }
//sorting!
        if (true === is_array($sorted)) {
            $tmp_result = array();
            foreach ($result as $r) {
                $tmp_result[$r->msgno] = $r;
            }

            $result = array();
            foreach ($msgs as $msgno) {
                $result[] = $tmp_result[$msgno];
            }
        }

        $return = array('res' => $result,
            'start' => $start,
            'limit' => $limit,
            'sorting' => array('by' => $sort[0], 'direction' => $sort[1]),
            'total' => imap_num_msg($this->marubox));
        $return['pages'] = ceil($return['total'] / $per_page);
        return $return;
    }

    function getHeaders($mid) {
        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') {
            $mail_details = array(
                'from' => strtolower($sender->mailbox) . '@' . $sender->host,
                'fromName' => $sender->personal,
                'toOth' => strtolower($sender_replyto->mailbox) . '@' . $sender_replyto->host,
                'toNameOth' => $sender_replyto->personal,
                'subject' => $mail_header->subject,
                '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) {
            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);
                } else if ($structure->encoding == 4) {
                    return imap_qprint($text);
                } else {
                    return $text;
                }
            }
            if ($structure->type == 1) /* multipart */ {
                while (list($index, $sub_structure) = each($structure->parts)) {
                    $prefix = '';
                    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() {
        if (!$this->marubox)
            return false;

        $headers = imap_headers($this->marubox);

        $mail_list = imap_listmailbox($this->marubox, "{imap.qq.com}", '*');
        print_r("<pre>");
        print_r($mail_list);
        return count($headers);
    }

    function GetAttach($mid, $path) { // Get Atteced File from Mail
        if (!$this->marubox) {
            return false;
        }

        $struckture = imap_fetchstructure($this->marubox, $mid);
        $ar = "";
        if ($struckture->parts) {
            foreach ($struckture->parts as $key => $value) {
                $enc = $struckture->parts[$key]->encoding;
                if ($struckture->parts[$key]->subtype == 'OCTET-STREAM') {
                    $name = base64_decode($struckture->parts[$key]->parameters[1]->value);
                    $name = iconv("gbk", 'utf-8', $name);
                    $name = substr($name, 7); // 未知原因 base64解密以后字符串前边多了三个 乱码字符    截取7以后的字符串
                    $message = imap_fetchbody($this->marubox, $mid, $key + 1);
                    switch ($enc) {
                        case 0:
                            $message = imap_8bit($message);
                            break;
                        case 1:
                            $message = imap_8bit($message);
                            break;
                        case 2:
                            $message = imap_binary($message);
                            break;
                        case 3:
                            $message = imap_base64($message);
                            break;
                        case 4:
                            $message = quoted_printable_decode($message);
                            break;
                        case 5:
                            $message = $message;
                            break;
                    }
                    // 文件名转换
                    $name = explode('.', $name);
                    $firs_name = urlencode($name[0]);
                    $filename = $firs_name . '.' . $name[1];
                    if(!file_exists($path)){
                        mkdir($path,0777,true);
                    }
                    $fp = fopen($path . $filename, "w");  //fopen  中文文件名
                    fwrite($fp, $message);
                    fclose($fp);
                    $ar = $ar . $filename . ",";
                }
//                print_r("********************<br /> 进入测试区");
//
//                $mess = base64_decode("?gb18030?B?MjAxNDA2MTXW0Ln6uaTJzNL40NDM2NS8taXOu1BPU7270tfH5bWlMDUwMjAxMTIwMzcwXzAwMC5jc3Y=?=");
//                $mess = iconv("gbk", 'utf-8', $mess);
//
//                $mess = substr($mess, 7);
//                print_r($mess);
//                die();
//                $message = imap_fetchbody($this->marubox, $mid, $partnro);
//
//                print_r($key);

                /*
                 * @下边暂时禁用  // Support for embedded attachments starts here
                 */
//                if (isset($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 = $struckture->parts[$key]->parts[$keyb]->dparameters[0]->value;
//                            $partnro = ($key + 1) . "." . ($keyb + 1);
//                            $message = imap_fetchbody($this->marubox, $mid, $partnro);
//                            switch ($enc) {
//                                case 0:
//                                    $message = imap_8bit($message);
//                                    break;
//                                case 1:
//                                    $message = imap_8bit($message);
//                                    break;
//                                case 2:
//                                    $message = imap_binary($message);
//                                    break;
//                                case 3:
//                                    $message = imap_base64($message);
//                                    break;
//                                case 4:
//                                    $message = quoted_printable_decode($message);
//                                    break;
//                                case 5:
//                                    $message = $message;
//                                    break;
//                            }
//                            $fp = fopen($path . $name, "w");
//                            fwrite($fp, $message);
//                            fclose($fp);
//                            $ar = $ar . $name . ",";
//                        }
//                    }
//                }
            }
        }
        $ar = substr($ar, 0, (strlen($ar) - 1));
        return $ar;
    }

    function removeEamil($mid) {
        if (!$this->marubox)
            return false;

        imap_mail_move($this->marubox, $mid, '&UXZO1mWHTvZZOQ-/beifen');
    }

    function getBody($mid) { // 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 "";
        }
        return $this->_iconv_utf8($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 _imap_utf8($text) {
        if (preg_match('/=\?([a-zA-z0-9\-]+)\?(.*)\?=/i', $text, $match)) {
            $text = imap_utf8($text);
            if (strtolower(substr($match[1], 0, 2)) == 'gb') {
                $text = iconv('gbk', 'utf-8', $text);
            }
            return $text;
        }
        return $this->_iconv_utf8($text);
    }

    function _iconv_utf8($text) {
        $s1 = iconv('gbk', 'utf-8', $text);
        $s0 = iconv('utf-8', 'gbk', $s1);
        if ($s0 == $text) {
            return $s1;
        } else {
            return $text;
        }
    }

}


receivemail是一个专门用来接收邮件PHP类,支持POP3和IMAP等邮件协议。 可以接收邮件邮件附件。 include("receivemail.class.php"); 02 // 创建一个 reciveMail 对象 03 $obj = new receiveMail('abc@abc.com','xxxxxx','abc@abc.com','pop.abc.com','pop3','110',false); 04 // 连接到邮件服务器 05 $obj->connect(); //If connection fails give error message and exit 06 // 读取未读邮件数 07 $tot = $obj->getTotalMails(); //Total Mails in Inbox Return integer value 08 09 echo "收到$tot封邮件::"; 10 for($i = $tot; $i > 0; $i--) 11 { 12 $head = $obj->getHeaders($i); // 读取获取邮件头信息,返回数组 **数组键值为 (subject,to,toOth,toNameOth,from,fromName) 13 echo "主题 :: ".$head['subject'].""; 14 echo "收件人 :: ".$head['to'].""; 15 echo "抄送 :: ".$head['toOth'].""; 16 echo "发件人 :: ".$head['from'].""; 17 echo "发件人名称 :: ".$head['fromName'].""; 18 echo ""; 19 echo "*******************************************************************************************"; 20 echo $obj->getBody($i); // 邮件正文 21 $str = $obj->GetAttach($i,"./"); // 获取邮件附件,返回的文件名以逗号隔开。 例如. (mailid, Path to store file) 22 $ar = explode(",",$str); 23 foreach($ar as $key=>$value) 24 echo ($value == "") ? "" : "Atteched File :: " . $value . ""; 25 echo "------------------------------------------------------------------------------------------"; 26 //$obj->deleteMails($i); // Delete Mail from Mail box 27 } 28 $obj->close_mailbox(); //Close Mail Box
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值