0

0

一个邮件解码类

php中文网

php中文网

发布时间:2016-06-21 09:05:51

|

924人浏览过

|

来源于php中文网

原创

 
    /**这个是改自pear中的解码类,增加了多种解码方式,修正了源码的系列bug.将解出的邮件分正文和附件存储,提高了解码效率。
    * mime decode class
    *
    * this class used at undecode mime files
    * useage:
    *
    *    $message=getmessage($filename,$read_type,$read_size);    
    *    $structure=rdmail($message);
    *    $from=$structure->headers['from'];
    *    $to=$structure->headers['to'];
    *
    * @copyright (c) 2004, richard,bjcctv. all rights reserved.
    * @author richard,bjcctv
    * @date:2004-11-24 last modified at:2005-06-01
    * @package mimedecode
    * @version $id$
    */
 
class decode_mimemail
{
 
    /**
     * mime file
     * @var    string
     */
    var $_input;
 
    /**
     * header string
     * @var    string
     */
    var $_header;
 
    /**
     * body string
     * @var    string
     */
    var $_body;
 
    /**
     * err info
     * @var    string
     */
    var $_error;
 
    /**
     * whether include body object
     * @var    boolean
     */
    var $_include_bodies;
 
    /**
     * whether include body object
     * @var    boolean
     */
    var $_decode_bodies;
 
    /**
     * whether decode headers object
     * @var    boolean
     */
    var $_decode_headers;
 
    /**
     * crlf variable
     * @var    string
     */
    var $_crlf;
 
    /**
     * body parts
     * @var object
     */
    var $parts;
    var $mid;
    var $maildir;
 
    /**
     * constructor.
     *
     * sets up the object, initialise the variables, and splits and
     * stores the header and body of the input.
     *
     * @param string the input to decode
     * @access public
     */
     
    function decode_mimemail($input, $mid, $maildir, $crlf = "\n")
    {
        $this->_crlf   = "\n";
        list($header, $body)    = $this->splitbodyheader($input); //拆分信头和信体两块
        $this->_input            = $input;
        $this->_header            = $header;
        $this->_body            = $body;
        $this->mid                = $mid;
        $this->maildir            = $maildir;
        $this->_decode_bodies    = false;
        $this->_include_bodies    = true;
    }
 
    /**
     * begins the decoding process. if called statically
     * it will create an object and call the decode() method
     * of it.
     *
     * @param array an array of various parameters that determine
     *              various things:
     *              include_bodies - whether to include the body in the returned
     *                               object.
     *              decode_bodies  - whether to decode the bodies
     *                               of the parts. (transfer encoding)
     *              decode_headers - whether to decode headers
     *              input          - if called statically, this will be treated
     *                               as the input
     * @return object decoded results
     * @access public
     */
    
    function decode($params = null)
    {
        // have we been called statically?
        // if so, create an object and pass details to that.
        if (!isset($this) and isset($params['input']))
        {
            if (isset($params['crlf']))
            {
                $obj = new decode_mimemail($params['input'],$params['mid'],$params['maildir'],$params['crlf']);
            }
            else
            {
                $obj = new decode_mimemail($params['input'],$params['mid'],$params['maildir']);
            }
            $structure = $obj->decode($params);
 
        // called statically but no input
        }
        elseif (!isset($this))
        {
            return $this->_error="called statically and no input given";
 
        // called via an object
        }
        else
        {
            $this->_include_bodies = isset($params['include_bodies'])
                                        ? $params['include_bodies']
                                        : false;
            $this->_decode_bodies  = isset($params['decode_bodies'])
                                        ? $params['decode_bodies']
                                        : false;
            $this->_decode_headers = isset($params['decode_headers'])
                                        ? $params['decode_headers']
                                        : false;
            if (is_null($this->_header) || is_null($this->_body)
                || is_null($this->mid) || is_null($this->maildir))
            {
                    $structure = false;
            }
            else
            {
                $structure = $this->_decode($this->_header, $this->_body, $this->mid, $this->maildir);
            }
            if($structure === false)
            {
                $structure = $this->_error;
            }
        }
        return $structure;
    }
 
    /**
     * performs the decoding. decodes the body string passed to it
     * if it finds certain content-types it will call itself in a
     * recursive fashion
     *
     * @param string header section
     * @param string body section
     * @param string mid mime filename
     * @return object results of decoding process
     * @access private
     */
 
    function _decode($headers, $body, $mid, $maildir, $default_ctype = 'text/plain')
    {
        $return = new stdclass;
        if(!is_null($headers))
        {
            $headers = $this->parseheaders($headers);
        }
        else{
            $this->_error="the mime headers is null.";
            return $this->_error;
        }
 
        foreach ($headers as $value)
        {
            if (isset($return->headers[$value['name']]) and !is_array($return->headers[$value['name']]))
            {
                $return->headers[$value['name']]   = array($return->headers[$value['name']]);
                $return->headers[$value['name']][] = $value['value'];
            }
            elseif (isset($return->headers[$value['name']]))
            {
                $return->headers[$value['name']][] = $value['value'];
            }
            else
            {
                $return->headers[$value['name']] = $value['value'];
            }
        }
        reset($headers); 
        //rewinds array's internal pointer to the first element and returns the value of the first array element. 
        while (list($key, $value) = each($headers))
        {
            $headers[$key]['name'] = strtolower($headers[$key]['name']); 
            switch ($headers[$key]['name'])
            {
                case 'content-type':
                    $content_type = $this->parseheadervalue($headers[$key]['value']); 
                    if (preg_match('/([0-9a-z+.-]+)/([0-9a-z+.-]+)/i', $content_type['value'], $regs))
                    {
                        $return->ctype_primary   = $regs[1];
                        $return->ctype_secondary = $regs[2];
                    }
                    if (isset($content_type['other']))
                    {
                        while (list($p_name, $p_value) = each($content_type['other']))
                        {
                            $return->ctype_parameters[$p_name] = $p_value;
                        }
                    }
                    break;
 
                case 'content-disposition':
                    $content_disposition = $this->parseheadervalue($headers[$key]['value']);
                    $return->disposition   = $content_disposition['value'];
                    if (isset($content_disposition['other']))
                    {
                        while (list($p_name, $p_value) = each($content_disposition['other'])) 
                        {
                            $return->d_parameters[$p_name] = $p_value;
                        }
                    }
                    break;
                case 'content-transfer-encoding':
                    if(!is_null($this->parseheadervalue($headers[$key]['value'])))
                    {
                        $content_transfer_encoding = $this->parseheadervalue($headers[$key]['value']);
                    }
                    else{
                        $content_transfer_encoding = "";
                    }
                    break;
            }
        }
        if (isset($content_type))
        {
            $content_type['value'] = strtolower($content_type['value']);
            switch ($content_type['value'])
            {
                case 'text':
                case 'text/plain':
                    if($this->_include_bodies)
                    {
                        if($this->_decode_bodies)
                        {
                            $return->body = isset($content_transfer_encoding['value'])
                                        ?$this->decodebody($body,$content_transfer_encoding['value'])
                                        : $body;
                        }
                        else{
                            $return->body = $body;
                        }
                        
                        if(!isset($content_type['other']['charset']))
                        {
                            $content_type['other']['charset']="gb2312";
                        }
                        if($content_type['other']['charset'] != "")
                        {
                            $orim_str = "----- original message -----";
                            $orim_startpos = strpos($return->body,$orim_str);
                            if(is_int($orim_startpos))
                            {
                                $return->body = $return->body;
                            }
                            else{
                                $return->body    = str_replace("body);
                                $return->body    = str_replace(">",">",$return->body);
                                $return->body    = str_replace("\n","
",$return->body);
                                $return->body    = str_replace(" ","   ",$return->body);
                            }
                        }
                    }
                    $return->body = $this->converurltolink($return->body);
                     $return->body    = str_replace("
","
",$return->body);
                     $return->body    = str_replace("   "," ",$return->body);
                    if(strtolower($return->ctype_parameters['charset'])=="utf-8")
                    {
                        $return->body=iconv("utf-8", "gb2312", $return->body);
                    }                 
                    break;
    
                case 'text/html':
                    if($this->_include_bodies)
                    {
                        if($this->_decode_bodies)
                        {
                            $return->body = isset($content_transfer_encoding['value'])
                                        ? $this->decodebody($body,$content_transfer_encoding['value'])
                                        : $body;
                        }
                        else{
                            $return->body = $body;
                        }
                    }
                    $return->body = $this->converurltolink($return->body);                
                    if(strtolower($return->ctype_parameters['charset'])=="utf-8")
                    {
                        $return->body=iconv("utf-8", "gb2312", $return->body);
                    }
                    break;
                case 'multipart/mixed':
                case 'multipart/alternative':
                case 'multipart/digest':
                case 'multipart/parallel':
                case 'multipart/report': // rfc1892
                case 'multipart/signed': // pgp
                case 'multipart/related':
                case 'application/x-pkcs7-mime':
                    if(!isset($content_type['other']['boundary']))
                    {
                        $this->_error = 'no boundary found for '.$content_type['value'].' part';
                        return false;
                    }
                    $default_ctype = (strtolower($content_type['value']) === 'multipart/digest')
                                        ? 'message/rfc822'
                                        : 'text/plain';
                    $parts = $this->boundarysplit($body, $content_type['other']['boundary']);
                    
                    if(!isset($return->attlist))
                    {
                        $return->attlist="";
                    }
                    for ($i = 0; $i                     {
                        list($part_header, $part_body) = $this->splitbodyheader($parts[$i]);
                        if (is_null($part_header) || is_null($part_body))
                        {
                            $part = false;
                        }
                        else
                        {
                            $part = $this->_decode($part_header, $part_body, $mid, $maildir, $default_ctype);
                        }
                           if($part === false)
                        {
                               $part =$this->_error;   
                        }
                        if(!is_null($part->ctype_primary) and !is_null($part->ctype_secondary))
                        {
                            $part_content_type=$part->ctype_primary."/".$part->ctype_secondary;
                        }
                        else{
                            $part_content_type="";
                        }
 
                        if(isset($part->body))
                        {
                            if(isset($part->headers['content-transfer-encoding']) and !is_null($part->headers['content-transfer-encoding']))
                            {
                                $part->body    = $this->decodebody($part->body,$part->headers['content-transfer-encoding']);
                            }
                            else{
                                $part->body    = $part->body;
                            }
                        }
                        /**
                         * if part exists with filename/name,save to disk.
                         */
                        if(!isset($part->body))
                        {
                            $part->body = $this->decodebody($part_body, "base64");
                        } 
                        
                        if((($part->ctype_primary."/".$part->ctype_secondary=="message/rfc822") or ($part->ctype_parameters['name']!="") or ($part->headers['content-id']!="") or (isset($part->d_parameters['filename']) and isset($part->disposition))) and isset($part->body))
                        {                    
                            $att_savename= $mid.".att".$i;    //attachment save name.
                            $user_cache=$this->maildir;
                            if(!empty($user_cache) and !empty($att_savename))
                            {
                                $att_file=$user_cache."/".$att_savename;
                            }
                            else
                            {
                                $att_file="";
                                $return->parts[] = $part;
                                break;
                            }
                            $att_filename    = $part->ctype_parameters['name'];
                            if($att_filename=="")
                            {
                                $att_filename = $part->d_parameters['filename']==""
                                                ? $att_filename = "autofile".$i
                                                : $part->d_parameters['filename'];
                                //if the attachment is the type of rfc/822,and filename is null
                                //rename to autofile with ".eml"
                                if(($part->ctype_primary."/".$part->ctype_secondary=="message/rfc822") and $att_filename=="autofile".$i)
                                {
                                    $att_filename = $att_filename.".eml";  
                                }
                            }
                            $this->createattfiles($att_file,$part->body);
     ,                        $attfile_size=filesize($att_file);
                            $return->attlist.=$att_filename."|".$attfile_size."|".$att_savename."|".$part_content_type."\n";
                            $logname=$user_cache."/.attlog";
                            $logcontent = $att_savename."\n";
                            $this->createlog($logname,$logcontent);
                            $part->body = ""; //released the used memory
                        }
                        else
                        {
                            if(isset($part->body))
                            {
                                $return->body=$part->body;
                            }
                        }
                        $return->parts[] = $part;
                    }
                    break;
                  case 'image/gif':
                  case 'image/jpeg':
                    break;
                default:
                    if($this->_include_bodies)
                    {
                        if($this->_decode_bodies)
                        {
                            $return->body = isset($content_transfer_encoding['value'])
                                        ?$this->decodebody($body,$content_transfer_encoding['value'])
                                        :$body;
                        }
                        else{
                            $return->body = $body;
                        }
                    }
                    break;
            } // end switch
 
        }
        else {
            //process if content-type isn't exist.
            $ctype = explode('/', $default_ctype);
            $return->ctype_primary   = $ctype[0];
            $return->ctype_secondary = $ctype[1];
            $this->_include_bodies
                ? $return->body = ($this->_decode_bodies
                                    ? $this->decodebody($body)
                                    : $body)
                : null;
                if($this->_include_bodies)
                {
                    $orim_str = "----- original message -----";
                    $orim_startpos = strpos($return->body,$orim_str);
                    if(is_int($orim_startpos))
                    {
                        $return->body = $return->body;
                    }
                    else{
                        $return->body    = str_replace("\n","
",$return->body);
                        $return->body    = str_replace(" ","   ",$return->body);
                    }
                }
                $return->body    = $this->converurltolink($return->body);
                 $return->body    = str_replace("
","
",$return->body);
                 $return->body    = str_replace("   "," ",$return->body);
                if(strtolower($return->ctype_parameters['charset'])=="utf-8")
                {
                      $return->body=iconv("utf-8", "gb2312", $return->body);
                }                 
        } //end else
       if(0attlist))
       {        
               $return->attlist  = substr($return->attlist,0,(strlen($return->attlist)-1)); 
       }   
       return $return;
    }
 
    /**
     * given a string containing a header and body
     * section, this function will split them (at the first blank line) and return them.
     *
     * @param string input to split apart
     * @return array contains header and body section
     * @access private
     */
 
    function splitbodyheader($input)
    {
        $pos = strpos($input, $this->_crlf.$this->_crlf);
        if ($pos === false)
        {
            $this->_error = 'could not split header and body';
            return false;
        }
 
        $header = substr($input, 0, $pos);
        $body   = substr($input, $pos+(2*strlen($this->_crlf)));
        return array($header, $body);
    }
 
    /**
     * parse headers given in $input and return as assoc array.
     *
     * @param string headers to parse
     * @return array contains parsed headers
     * @access private
     */
 
    function parseheaders($input)
    {
        if ($input !== '')
        {
            // unfold the input
            $input   = preg_replace('/' . $this->_crlf . "(\t| )/", ' ', $input);
            $headers = explode($this->_crlf, trim($input));
 
            foreach ($headers as $value)
            {
                $hdr_name = strtolower(substr($value, 0, $pos = strpos($value, ':')));
                $hdr_value = substr($value, $pos+1);
                $return[] = array(
                                  'name'  => $hdr_name,
                                  'value' => $this->_decode_headers
                                                ? $this->decodeheader($hdr_value)
                                             &nbs

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法
pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法

本专题系统整理pixiv网页版官网入口及登录访问方式,涵盖官网登录页面直达路径、在线阅读入口及快速进入方法说明,帮助用户高效找到pixiv官方网站,实现便捷、安全的网页端浏览与账号登录体验。

286

2026.02.13

微博网页版主页入口与登录指南_官方网页端快速访问方法
微博网页版主页入口与登录指南_官方网页端快速访问方法

本专题系统整理微博网页版官方入口及网页端登录方式,涵盖首页直达地址、账号登录流程与常见访问问题说明,帮助用户快速找到微博官网主页,实现便捷、安全的网页端登录与内容浏览体验。

126

2026.02.13

Flutter跨平台开发与状态管理实战
Flutter跨平台开发与状态管理实战

本专题围绕Flutter框架展开,系统讲解跨平台UI构建原理与状态管理方案。内容涵盖Widget生命周期、路由管理、Provider与Bloc状态管理模式、网络请求封装及性能优化技巧。通过实战项目演示,帮助开发者构建流畅、可维护的跨平台移动应用。

42

2026.02.13

TypeScript工程化开发与Vite构建优化实践
TypeScript工程化开发与Vite构建优化实践

本专题面向前端开发者,深入讲解 TypeScript 类型系统与大型项目结构设计方法,并结合 Vite 构建工具优化前端工程化流程。内容包括模块化设计、类型声明管理、代码分割、热更新原理以及构建性能调优。通过完整项目示例,帮助开发者提升代码可维护性与开发效率。

19

2026.02.13

Redis高可用架构与分布式缓存实战
Redis高可用架构与分布式缓存实战

本专题围绕 Redis 在高并发系统中的应用展开,系统讲解主从复制、哨兵机制、Cluster 集群模式及数据分片原理。内容涵盖缓存穿透与雪崩解决方案、分布式锁实现、热点数据优化及持久化策略。通过真实业务场景演示,帮助开发者构建高可用、可扩展的分布式缓存系统。

23

2026.02.13

c语言 数据类型
c语言 数据类型

本专题整合了c语言数据类型相关内容,阅读专题下面的文章了解更多详细内容。

29

2026.02.12

雨课堂网页版登录入口与使用指南_官方在线教学平台访问方法
雨课堂网页版登录入口与使用指南_官方在线教学平台访问方法

本专题系统整理雨课堂网页版官方入口及在线登录方式,涵盖账号登录流程、官方直连入口及平台访问方法说明,帮助师生用户快速进入雨课堂在线教学平台,实现便捷、高效的课程学习与教学管理体验。

14

2026.02.12

豆包AI网页版入口与智能创作指南_官方在线写作与图片生成使用方法
豆包AI网页版入口与智能创作指南_官方在线写作与图片生成使用方法

本专题汇总豆包AI官方网页版入口及在线使用方式,涵盖智能写作工具、图片生成体验入口和官网登录方法,帮助用户快速直达豆包AI平台,高效完成文本创作与AI生图任务,实现便捷智能创作体验。

421

2026.02.12

PostgreSQL性能优化与索引调优实战
PostgreSQL性能优化与索引调优实战

本专题面向后端开发与数据库工程师,深入讲解 PostgreSQL 查询优化原理与索引机制。内容包括执行计划分析、常见索引类型对比、慢查询优化策略、事务隔离级别以及高并发场景下的性能调优技巧。通过实战案例解析,帮助开发者提升数据库响应速度与系统稳定性。

51

2026.02.12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号