当前位置: 首页 > 工具软件 > IMAP Upload > 使用案例 >

imap读取邮件内容(修改源码后附件做了处理)

卢阳成
2023-12-01

一,类文件

Receivemail.php

<?php
namespace modules\Sms\models;
// use yii\data\Pagination;
use yii;

class Receivemail
{
    var $server='';
    var $username='';
    var $password='';

    var $marubox='';

    var $email='';

    public function __construct($username, $password, $EmailAddress, $mailserver = 'localhost', $servertype = 'pop', $port = '110', $ssl = false)
    { //Constructure
        if ($servertype == 'imap') {
            if ($port == '')
                $port = '143';
            $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() //Connect To the Mail Box
    {
        $this->marubox=@imap_open($this->server,$this->username,$this->password);

        if(!$this->marubox)
        {
            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)!='mailer-daemon' && strtolower($sender->mailbox)!='postmaster') {
            $subject=$this->decode_mime($mail_header->subject);
            $ccList=array();
            foreach ($mail_header->cc as $k => $v) {
                $ccList[]=$v->mailbox.'@'.$v->host;
            }
            $toList=array();
            foreach ($mail_header->to as $k => $v) {
                $toList[]=$v->mailbox.'@'.$v->host;
            }
            $ccList=implode(",", $ccList);
            $toList=implode(",", $toList);
            $mail_details=array(
                'fromBy'=>strtolower($sender->mailbox).'@'.$sender->host,
                'fromName'=>$this->decode_mime($sender->personal),
                'ccList'=>$ccList,
                'toNameOth'=>$this->decode_mime($sender_replyto->personal),
                'subject'=>$subject,
                'mailDate'=>date("Y-m-d H:i:s",$mail_header->udate),
                'udate'=>$mail_header->udate,
                'toList'=>$toList,
               'seen' => $mail_header->Unseen
            );
        }
        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] . '/' . $structure->subtype;
        }
        return "TEXT/PLAIN";
    }


    function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false)
    {
        if(!$structure) {
            $structure = imap_fetchstructure($stream, $msg_number);
        }
        if($structure) {
            if($mime_type == $this->get_mime_type($structure)) {
                if(!$part_number) {
                    $part_number = "1";
                }
                $fromEncoding = $structure->parameters[0]->value;
                $text = imap_fetchbody($stream, $msg_number, $part_number);

                if($structure->encoding == 3) {
                    $text = imap_base64($text);
                } else if($structure->encoding == 4) {
                    $text = imap_qprint($text);
                }
                $text = mb_convert_encoding($text, 'utf-8', $fromEncoding);
                return $text;
            }
            if($structure->type == 1) {
                while(list($index, $sub_structure) = each($structure->parts)) {
                    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;
        }
        $check = imap_check($this->marubox);
        return $check->Nmsgs;
    }

    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['extension'] = $extend[count($extend)-1];
                    $file['pathname']  = $this->setPathName($key, $file['extension']);
                    $file['title']     = !empty($name) ? htmlspecialchars($name) : str_replace('.' . $file['extension'], '', $name);
                    $file['size']      = $struckture->parts[$key]->dparameters[1]->value;
// 					$file['tmpname']   = $struckture->parts[$key]->dparameters[0]->value;
                    if(@$struckture->parts[$key]->disposition=="ATTACHMENT") {
                        $file['type']      = 1;
                    } else {
                        $file['type']      = 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['pathname'],"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['extension'] = $extend[count($extend)-1];
                            $file['pathname']  = $this->setPathName($key, $file['extension']);
                            $file['title']     = !empty($name) ? htmlspecialchars($name) : str_replace('.' . $file['extension'], '', $name);
                            $file['size']      = $struckture->parts[$key]->parts[$keyb]->dparameters[1]->value;
// 							$file['tmpname']   = $struckture->parts[$key]->dparameters[0]->value;
                            $file['type']      = 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['pathname'],"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('/<img.*?>/', $body, $matches);

        if (!isset($matches[0])) return;

        foreach ($matches[0] as $img) {
            // replace image web path with local path
            preg_match('/src="(.*?)"/', $img, $m);
            if (!isset($m[1])) continue;
            $arr = parse_url($m[1]);
//            var_dump($arr);
            if (!isset($arr['scheme']) || !isset($arr['path']))continue;

// 			if (!isset($arr['host']) || !isset($arr['path']))continue;
            if ($arr['scheme']!="http" && $arr['scheme']!="https")
            {
                $filename=explode("@", $arr['path']);
                $body = str_replace($img, '<img alt="" src="'.$path.$imageList[$filename[0]].'" style="border: none;" />', $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);
        if ($str[0]->charset != "UTF-8") {
            return mb_convert_encoding($str[0]->text,'utf8',$str[0]->charset);
        } 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('Ym/dHis', time()) . $fileID . mt_rand(0, 10000) . '.' . $extension;
    }

    public function mailRead($msgCount) {
        $status = imap_setflag_full($this->marubox, $msgCount, "\\Seen");
        return $status;
    }

}
?>

二,控制器文件 EmController.php

<?php
//@header('Content-type: text/html;charset=UTF-8');
//error_reporting(0);
//ignore_user_abort(); // run script in background
//set_time_limit(0); // run script forever
//date_default_timezone_set('Asia/Shanghai');
namespace modules\Sms\controllers;

use yii;
use yii\base\Controller;
use modules\Sms\models\Receivemail;
use modules\Sms\models\Email;
use app\models\Attachment;

class EmController extends Controller
{
    //定义系统常量
    //用户名
    public $mailAccount = "********";
    public $mailPasswd = "*******";
    public $mailAddress = "******@qq.com";
    public $mailServer = "imap.qq.com";
    public $serverType = "imap";
    public $port = "993";
    public $now = '';
    public $savePath = '';
    public $webPath = "./upload/";
    public $user = '';

    public function init()
    {
        $this->now = time();
        $this->user = getUserInfo();
        $this->setSavePath();
    }

    public function actionIndex()
    {
        $obj = new static(); //self();
        $res = $obj->mailReceived();
        var_dump($res);
    }

    /**
     * mail Received()读取收件箱邮件
     *
     * @param
     * @access public
     * @return result
     */
    public function mailReceived()
    {
        $obj = new Receivemail($this->mailAccount, $this->mailPasswd, $this->mailAddress, $this->mailServer, $this->serverType, $this->port, false);
        $obj->connect();
        $tot = $obj->getTotalMails();

        if ($tot == 0) { //如果信件数为0,显示信息
            return array("msg" => "邮件数量 " . $this->mailAccount);
        } else {
            $res = array("msg" => "邮件数量:: $tot<br>");
            for ($i = $tot; $i > 0; $i--) {
                $head = $obj->getHeaders($i);

                if ($head['seen'] != "U") {  //取未读邮件内容
                    //处理邮件附件
                    $files = $obj->GetAttach($i, $this->savePath);
                    // 获取邮件附件,返回的邮件附件信息数组
                    $imageList = array();
                    foreach ($files as $k => $file) {
                        //type=1为附件,0为邮件内容图片
                        if ($file['type'] == 0) {
                            $imageList[$file['title']] = $file['pathname'];
                        }
                    }

                    if ($files) {
                        $fileid = $this->saveFile($files); //附件入库
                    }
                    $body = $obj->getBody($i, $this->webPath, $imageList);
                    $status = $obj->mailRead($i);
                    $res['mail'][] = array('head' => $head, 'body' => $body, "attachList" => $files);
                    $this->saveData($head, $body, $fileid);
                }
            }

            $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('Ym/', $this->now);
        if (!file_exists($savePath)) {
            @mkdir($savePath, 0777, true);
            touch($savePath . 'index.html');
        }
        $this->savePath = dirname($savePath) . '/';
    }

    /**
     * 附件入库
     */

    public function saveFile($file)
    {
        $attachment = new Attachment();
        $file_temp['module'] = Yii::$app->controller->module->id;
        $file_temp['filename'] = $file[0]['title'];
        $file_temp['filepath'] = ltrim($this->savePath, '.') . $file[0]['pathname'];
        $file_temp['fileext'] = $file[0]['extension'];
        $file_temp['userid'] = $this->user['userid'];
        $file_temp['username'] = $this->user['realname'] . '(' . $this->user['username'] . ')';
        $file_temp['uploadtime'] = time();
        $file_temp['uploadip'] = ip();
        $file_temp['authcode'] = MD5($this->savePath);
        $file_result = $attachment->addData($file_temp);
        if (!$file_result) {
            $this->error('添加附件数据错误');
        }
        return $file_result;
    }

    /*
     * 入库
     */
    public function saveData($head, $body, $fileid)
    {
        $fileid = $fileid ? $fileid : '';
        $email_model = new Email();
        $data = ['from' => $head['fromBy'], 'to' => $head['toList'], 'title' => $head['subject'], 'body' => $body, 'fileids' => $fileid, 'date' => time()];
        $email_model->addData($data);
    }

}

?>

IMAP函数库:

  1. imap_append:  附加字符串到指定的邮箱中。
  2. imap_base64:  解 BASE64 编码。
  3. imap_body:  读信的内文。
  4. imap_check:  返回邮箱信息。
  5. imap_close:  关闭 IMAP 链接。
  6. imap_createmailbox:  建立新的信箱。
  7. imap_delete:  标记欲删除邮件。
  8. imap_deletemailbox:  删除既有信箱。
  9. imap_expunge:  删除已标记的邮件。
  10. imap_fetchbody:  从信件内文取出指定部分。
  11. imap_fetchstructure:  获取某信件的结构信息。
  12. imap_header:  获取某信件的标头信息。
  13. imap_headers:  获取全部信件的标头信息。
  14. imap_listmailbox:  获取邮箱列示。
  15. imap_listsubscribed:  获取订阅邮箱列示。
  16. imap_mail_copy:  复制指定信件到它处邮箱。
  17. imap_mail_move:  移动指定信件到它处邮箱。
  18. imap_num_msg:  取得信件数。
  19. imap_num_recent:  取得新进信件数。
  20. imap_open:  打开 IMAP 链接。
  21. imap_ping:  检查 IMAP 是否连接。
  22. imap_renamemailbox:  更改邮箱名字。
  23. imap_reopen:  重开 IMAP 链接。
  24. imap_subscribe:  订阅邮箱。
  25. imap_undelete:  取消删除邮件标记。
  26. imap_unsubscribe:  取消订阅邮箱。
  27. imap_qprint:  将 qp 编码转成八位。
  28. imap_8bit:  将八位转成 qp 编码。
  29. imap_binary:  将八位转成 base64 编码。
  30. imap_scanmailbox:  寻找信件有无特定字符串。
  31. imap_mailboxmsginfo:  取得目前邮箱的信息。
  32. imap_rfc822_write_address:  电子邮件位址标准化。
  33. imap_rfc822_parse_adrlist:  解析电子邮件位址。
  34. imap_setflag_full:  配置信件标志。
  35. imap_clearflag_full:  清除信件标志。
  36. imap_sort:  将信件标头排序。
  37. imap_fetchheader:  取得原始标头。
  38. imap_uid:  取得信件 UID。
  39. imap_getmailboxes:  取得全部信件详细信息。
  40. imap_getsubscribed:  列出所有订阅邮箱。
  41. imap_msgno:  列出 UID 的连续信件。
  42. imap_search:  搜寻指定标准的信件。
  43. imap_last_error:  最后的错误信息。
  44. imap_errors:  所有的错误信息。
  45. imap_alerts:  所有的警告信息。
  46. imap_status:  目前的状态信息。

 类似资料: