Home php教程 php手册 邮件接收类

邮件接收类

Jun 06, 2016 pm 07:31 PM
code Revise turn up take over Own mail

根据网上找到的代码自己修改了一点。 添加了所有编码统一转换为utf-8进行保存。 支持嵌入式附件 无 源码与演示: 源码出处 ?php/** * NOTICE OF LICENSE * * THIS SOURCE FILE IS PART OF EVEBIT'S PRIVATE PROJECT. * * DO NOT USE THIS FILE IN OTHER PLACE

根据网上找到的代码自己修改了一点。
添加了所有编码统一转换为utf-8进行保存。
支持嵌入式附件

源码与演示:源码出处

<?php
/**
  * NOTICE OF LICENSE
  *
  * THIS SOURCE FILE IS PART OF EVEBIT'S PRIVATE PROJECT.
  *
  * DO NOT USE THIS FILE IN OTHER PLACE.
  *
  * @category    EveBit_Library
  * @package     Application
  * @author      Chen Qiao 
 * @version     $$Id: Email.PHP 175 2011-03-26 09:52:16Z chen.qiao $$
  * @copyright   Copyright (c) 2011 Evebit Inc. China (http://www.evebit.com)
  */
 
/**
  * Email class
  *
  * get mail total count,get mail list,get mail content,get mail attach
  *
  * For a example, if you want to get some specified email list.
  * 
 * $mail = new Evebit_Mail();
  * $mail->mailConnect($host,$port,$user,$pass,'INBOX',$ssl);
  * $mail->mail_list('5,9:20');
  * 
 *
  * show the five,and nine to twenty mail.
  * 
 * $mail->mail_list('5,9:20');
  * 
 *
  * @docinfo
  *
  * @package     Application
  * @author      Chen Qiao 
 * @version     $$Id: Email.PHP 175 2011-03-26 09:52:16Z chen.qiao $$
  */

 class receiveMail {
     
    /**
      * @var resource $_connect
      */
     private $_connect;
     /**
      * @var object $_mailInfo
      */
     private $_mailInfo;
     /**
      * @var int $_total_count
      */
     private $_total_count;
     /**
      * @var array $_total_count
      */
    /**
      * __construct of the class
      */
     public function __construct() {

     }
     
    /**
      * Open an IMAP stream to a mailbox
      *
      * @param string $host
      * @param string $port
      * @param string $user
      * @param string $pass
      * @param string $folder
      * @param string $ssl
      * @param string $pop
      * @return resource|bool
      */
     public function connect($host,$port,$user,$pass,$folder="INBOX",$ssl,$pop=false) {
         if($pop){
             $ssl = $pop.'/'.$ssl.'/novalidate-cert/notls';
         }
         $this->_connect = imap_open("{"."$host:$port/$ssl"."}$folder",$user,$pass);
         if(!$this->_connect) {
             //Evebit_Application::getSession()->addError('cannot connect: ' . imap_last_error());
             return false;   
        }
         return $this->_connect;
     }
     
    /**
      * Get information about the current mailbox
      *
      * @return object|bool
      */
     public function mailInfo(){
         $this->_mailInfo = imap_mailboxmsginfo($this->_connection);
         if(!$this->_mailInfo) {
             echo "get mailInfo failed: " . imap_last_error();
             return false;
         }
         return $this->_mailInfo;
     }

    /**
      * Read an overview of the information in the headers of the given message
      *
      * @param string $msg_range
      * @return array
      */
     public function mail_list($msg_range='')
     {
         if ($msg_range) {
             $range=$msg_range;
         } else {
             $this->mail_total_count();
             $range = "1:".$this->_total_count;
         }
         $overview  = imap_fetch_overview($this->_connect,$range);
         foreach ($overview  as $val) {
             $mail_list[$val->msgno]=$val->message_id;
         }
         return $mail_list;
     }
     
    /**
      * get the total count of the current mailbox
      *
      * @return int
      */
     public function mail_total_count(){
         $check = imap_check($this->_connect);
            $this->_total_count = $check->Nmsgs;
            return $this->_total_count;
     }
     
    /**
      * Read the header of the message
      *
      * @param string $msg_count
      * @return array
      */
     public function mail_header($msg_count) {
         $mail_header = array();
         $header=imap_header($this->_connect,$msg_count);
         if(strtolower($sender->mailbox)!='mailer-daemon' && strtolower($sender->mailbox)!='postmaster') {
			$mail_header['name']=$this->mail_decode($header -> subject);
			$mail_header['mid']=$header -> message_id;
			$mail_header['to']=$this->contact_conv($header -> to);
			$mail_header['from']=$this->contact_conv($header -> from);
			$mail_header['cc']=$this->contact_conv($header -> cc);
			$mail_header['reply_to']=$this->contact_conv($header -> reply_to);
			$create_time=explode(",",$header -> date);
			if (strlen($create_time[0])>6){
				$create_time=$create_time[0];	
			}else{
				$create_time=$create_time[1];	
			}
			$mail_header['create_time']=strtotime($create_time); 
			$subject = $header -> subject;
			$charset = substr($subject, stripos($subject, "=?") + 2, stripos($subject, "?", 3)-2); 
			$content=$this->get_body($msg_count);
			//$mail_header['content']=$this->auto_charset($content, $charset, 'utf-8'); 
			$mail_header['content']=$content;
         }
         return $mail_header;
     }
     
  /**
      * decode the subject of chinese
      *
      * @param string $subject
      * @return sting
      */
 function mail_decode($str) {
	if (stripos($str, 'GBK?B')) {
		$arr_temp = explode(" ", $str); 
		for ($i = 0;$i <= count($arr_temp);$i++) {
			$tmp = str_ireplace('=?GBK?B?', '', $arr_temp[$i]);
			$tmp = str_ireplace('=?', '', $tmp);
			$tmp2 = $tmp2 . auto_charset(base64_decode($tmp), 'gb2312', 'utf-8');
		} 
		return $tmp2 ;
	}
	if (stripos($str, 'GBK?Q')) {
		$arr_temp = explode(" ", $str); 
		for ($i = 0;$i <= count($arr_temp);$i++) {
			$tmp = str_ireplace('=?GBK?B?', '', $arr_temp[$i]);
			$tmp = str_ireplace('=?', '', $tmp);
			$tmp2 = $tmp2 . auto_charset(base64_decode($tmp), 'gb2312', 'utf-8');
		} 
		return $tmp2 ;
	}
	if (stripos($str, 'utf-8?B')) {
		$arr_temp = explode(" ", $str); 
		// dump($arr_temp[0]);
		for ($i = 0;$i <= count($arr_temp);$i++) {
			$tmp = str_ireplace('=?utf-8?B?', '', $arr_temp[$i]);
			$tmp = str_ireplace('=?', '', $tmp);
			$tmp2 = $tmp2 . base64_decode($tmp);
		} 
		return $tmp2 ;
	}
	if (stripos($str, 'utf-8?Q')) {
		$arr_temp = explode(" ", $str); 
		for ($i = 0;$i <= count($arr_temp);$i++) {
			$tmp = str_ireplace('=?utf-8?Q?', '', $arr_temp[$i]);
			$tmp = str_ireplace('=?', '', $tmp);
			$tmp = str_ireplace('?', '', $tmp);
			$tmp2 = $tmp2 . quoted_printable_decode($tmp);
		} 
		return $tmp2 ;
	} 
	if (stripos($str, 'gb2312?B')) {
		$arr_temp = explode(" ", $str); 
		for ($i = 0;$i <= count($arr_temp);$i++) {
			$tmp = str_ireplace('=?gb2312?B?', '', $arr_temp[$i]);
			$tmp = str_ireplace('=?', '', $tmp);
			$tmp2 = $tmp2 . auto_charset(base64_decode($tmp), 'gb2312', 'utf-8');
		}
		return $tmp2 ;
	}
	if (stripos($str, 'gb2312?Q')) {
		$arr_temp = explode(" ", $str); 
		for ($i = 0;$i <= count($arr_temp);$i++) {
			$tmp = str_ireplace('=?gb2312?Q?', '', $arr_temp[$i]);
			$tmp = str_ireplace('=?', '', $tmp);
			$tmp = str_ireplace('?', '', $tmp);
			$tmp2 = $tmp2 . auto_charset(quoted_printable_decode($tmp),'gb2312','utf-8');
		}
		return $tmp2 ;
	}
	if (stripos($str, 'gb18030?B')) {
		$arr_temp = explode(" ", $str); 
		// dump($arr_temp[0]);
		for ($i = 0;$i <= count($arr_temp);$i++) {
			$tmp = str_ireplace('=?gb18030?B?', '', $arr_temp[$i]);
			$tmp = str_ireplace('=?', '', $tmp);
			$tmp2 = $tmp2 . auto_charset(base64_decode($tmp), 'gb2312', 'utf-8');
		} 
		return $tmp2 ;
	}
	if (stripos($str, 'gb18030?Q')) {
		$arr_temp = explode(" ", $str); 
		for ($i = 0;$i <= count($arr_temp);$i++) {
			$tmp = str_ireplace('=?gb18030?Q?', '', $arr_temp[$i]);
			$tmp = str_ireplace('=?', '', $tmp);
			$tmp = str_ireplace('?', '', $tmp);
			$tmp2 = $tmp2 . auto_charset(quoted_printable_decode($tmp),'gb18030','utf-8');
		}
		return $tmp2 ;
	}
	return $str;
}

function auto_charset($fContents,$from,$to){
    $from   =  strtoupper($from)=='UTF8'? 'utf-8':$from;
    $to       =  strtoupper($to)=='UTF8'? 'utf-8':$to;
    if( strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents)) ){
        //如果编码相同或者非字符串标量则不转换
        return $fContents;
    }
    if(is_string($fContents) ) {
        if(function_exists('mb_convert_encoding')){
            return mb_convert_encoding ($fContents, $to, $from);
        }elseif(function_exists('iconv')){
            return iconv($from,$to,$fContents);
        }else{
            return $fContents;
        }
    }
    elseif(is_array($fContents)){
        foreach ( $fContents as $key => $val ) {
            $_key =     auto_charset($key,$from,$to);
            $fContents[$_key] = auto_charset($val,$from,$to);
            if($key != $_key )
                unset($fContents[$key]);
        }
        return $fContents;
    }
    else{
        return $fContents;
    }
}
    /**
      * Mark a message for deletion from current mailbox
      *
      * @param string $msg_count
      */
     public function delete($msg_count) {
         imap_delete($this->_connect,$msg_count);
     }
     
    /**
      * get attach of the message
      *
      * @param string $msg_count
      * @param string $path
      * @return array
      */
     public function get_attach($msg_count,$path) {
		if(!$this->_connect) 
			return false;
		$struckture = imap_fetchstructure($this->_connect,$msg_count);
		$ar="";
		if($struckture->parts)
        {
			foreach($struckture->parts as $key => $value)
			{
				$enc=$struckture->parts[$key]->encoding;
				if($struckture->parts[$key]->ifdparameters)
				{
					$name=$this->mail_decode($struckture->parts[$key]->dparameters[0]->value);
					$cid=$struckture->parts[$key]->id;
					$cid=substr($cid,1,strlen($cid)-2);
					$disposition=$struckture->parts[$key]->disposition;
					
					$name=$cid."_".$disposition."_".$name;
					$message = imap_fetchbody($this->_connect,$msg_count,$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.urlencode($name),"w");
					fwrite($fp,$message);
					fclose($fp);
					$ar=$ar.$name.",";
				}
				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->mail_decode($struckture->parts[$key]->parts[$keyb]->dparameters[0]->value);
							$id=$struckture->parts[$key]->parts[$keyb]->id;
							$disposition=$struckture->parts[$key]->parts[$keyb]->disposition;							
							
							$name=$id."_".$disposition."_".$name;
							$partnro = ($key+1).".".($keyb+1);
							$message = imap_fetchbody($this->_connect,$msg_count,$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.urlencode($name),"w");
							fwrite($fp,$message);
							fclose($fp);
							$ar=$ar.$name.",";
						}
					}
				}	
			}
		}
		$ar=substr($ar,0,(strlen($ar)-1));
		return $ar;
	}
     
    /**
      * download the attach of the mail to localhost
      *
      * @param string $file_path
      * @param string $message
      * @param string $name
      */
     public function down_attach($file_path,$name,$message) {
         if(is_dir($file_path)) {
             $file_open = fopen($file_path.$name,"w");
         } else {
             mkdir($file_path,"0777",true);
         }
         fwrite($file_open,$message);
         fclose($file_open);
     }
 
     
    /**
      * get the body of the message
      *
      * @param string $msg_count
      * @return string
      */
     public function get_body($msg_count) {
         $body = $this->get_part($msg_count, "TEXT/HTML");
         if ($body == '') {
             $body = $this->get_part($msg_count, "TEXT/PLAIN");
         }
         if ($body == ''){
             return '';
         }
         return $this->mail_decode($body);
     }
     
    /**
      * Read the structure of a particular message and fetch a particular
      * section of the body of the message
      *
      * @param string $msg_count
      * @param string $mime_type
      * @param object $structure
      * @param string $part_no
      * @return string|bool
      */
     private function get_part($msg_count, $mime_type, $structure = false, $part_no = false) {
         if(!$structure) {
             $structure = imap_fetchstructure($this->_connect, $msg_count);
         }
         if($structure) {
             if($mime_type == $this->get_mime_type($structure)) {
                 if(!$part_no) {
                     $part_no = "1";
                 }
                 $from_encoding = $structure->parameters[0]->value;
                 $text = imap_fetchbody($this->_connect, $msg_count, $part_no);
                 if($structure->encoding == 3) {
                     $text =  imap_base64($text);
                 } else if($structure->encoding == 4) {
                     $text =  imap_qprint($text);
                 }
                 $text = mb_convert_encoding($text,'utf-8',$from_encoding);
                 return $text;
             }
             if($structure->type == 1) {
                 while(list($index, $sub_structure) = each($structure->parts)) {
                     if($part_no) {
                         $prefix = $part_no . '.';
                     }
                     $data = $this->get_part($msg_count, $mime_type, $sub_structure, $prefix . ($index + 1));
                     if($data){
                         return $data;
                     }
                 }
             }
         }
         return false;
     }
     
    /**
      * get the subtype and type of the message structure
      *
      * @param object $structure
      */
     private function get_mime_type($structure) {
         $mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
         if($structure->subtype) {
             return $mime_type[(int) $structure->type] . '/' . $structure->subtype;
         }
         return "TEXT/PLAIN";
     }
     
    /**
      * put the message from unread to read
      *
      * @param string $msg_count
      * @return bool
      */
     public function mail_read($msg_count) {
         $status = imap_setflag_full($this->_connect, $msg_count , "//Seen");
         return $status;
     }
     
    /**
      * Close an IMAP stream
      */
     public    function close_mail() {
         imap_close($this->_connect,CL_EXPUNGE);
     }

	 function contact_conv($contact){
		foreach($contact as $vo) {
			if (isset($vo -> personal)) {
				$tmp = $tmp.$this->mail_decode($vo -> personal)."|".$vo -> mailbox . '@' . $vo -> host.';';
			} else {
				$tmp = $tmp.$this->mail_decode($vo -> mailbox)."|".$vo -> mailbox . '@' . $vo -> host.';';
			} 
			return $tmp;
		}
	}     
}
 
?>
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Outlook emails lost from control panel in Windows 11 Outlook emails lost from control panel in Windows 11 Feb 29, 2024 pm 03:16 PM

Is the Outlook mail icon missing from Windows 11's Control Panel? This unexpected situation has caused confusion and concern among some individuals who rely on OutlookMail for their communication needs. Why don't my Outlook emails show up in Control Panel? There may be several possible reasons why there are no Outlook mail icons in Control Panel: Outlook is not installed correctly. Installing Office applications from the Microsoft Store does not add the Mail applet to Control Panel. The location of the mlcfg32.cpl file in Control Panel is missing. The path to the mlcfg32.cpl file in the registry is incorrect. The operating system is not currently configured to run this application

How to change the personal name in the group on DingTalk_How to modify the personal name in the group on DingTalk How to change the personal name in the group on DingTalk_How to modify the personal name in the group on DingTalk Mar 29, 2024 pm 08:41 PM

1. First open DingTalk. 2. Open the group chat and click the three dots in the upper right corner. 3. Find my nickname in this group. 4. Click to enter to modify and save.

Can Douyin Blue V change its name? What are the steps to change the name of corporate Douyin Blue V account? Can Douyin Blue V change its name? What are the steps to change the name of corporate Douyin Blue V account? Mar 22, 2024 pm 12:51 PM

Douyin Blue V certification is the official certification of a company or brand on the Douyin platform, which helps enhance brand image and credibility. With the adjustment of corporate development strategy or the update of brand image, the company may want to change the name of Douyin Blue V certification. So, can Douyin Blue V change its name? The answer is yes. This article will introduce in detail the steps to modify the name of the enterprise Douyin Blue V account. 1. Can Douyin Blue V change its name? You can change the name of Douyin Blue V account. According to Douyin’s official regulations, corporate Blue V certified accounts can apply to change their account names after meeting certain conditions. Generally speaking, enterprises need to provide relevant supporting materials, such as business licenses, organization code certificates, etc., to prove the legality and necessity of changing the name. 2. What are the steps to modify the name of corporate Douyin Blue V account?

GE universal remote codes program on any device GE universal remote codes program on any device Mar 02, 2024 pm 01:58 PM

If you need to program any device remotely, this article will help you. We will share the top GE universal remote codes for programming any device. What is a GE remote control? GEUniversalRemote is a remote control that can be used to control multiple devices such as smart TVs, LG, Vizio, Sony, Blu-ray, DVD, DVR, Roku, AppleTV, streaming media players and more. GEUniversal remote controls come in various models with different features and functions. GEUniversalRemote can control up to four devices. Top Universal Remote Codes to Program on Any Device GE remotes come with a set of codes that allow them to work with different devices. you may

Win10 sleep time modification tips revealed Win10 sleep time modification tips revealed Mar 08, 2024 pm 06:39 PM

Win10 Sleep Time Modification Tips Revealed As one of the currently widely used operating systems, Windows 10 has a sleep function to help users save power and protect the screen when not using the computer. However, sometimes the default sleep time does not meet the needs of users, so it is particularly important to know how to modify the Win10 sleep time. This article will reveal the tips for modifying the sleep time of Win10, allowing you to easily customize the system’s sleep settings. 1. Modify Win10 sleep time through “Settings” First, the simplest fix

How to modify the address location of published products on Xianyu How to modify the address location of published products on Xianyu Mar 28, 2024 pm 03:36 PM

When publishing products on the Xianyu platform, users can customize the geographical location information of the product according to the actual situation, so that potential buyers can more accurately grasp the specific location of the product. Once the product is successfully put on the shelves, there is no need to worry if the seller's location changes. The Xianyu platform provides a flexible and convenient modification function. So when we want to modify the address of a published product, how do we modify it? This tutorial guide will provide you with a detailed step-by-step guide. I hope it can help. Everyone! How to modify the release product address in Xianyu? 1. Open Xianyu, click on what I published, select the product, and click Edit. 2. Click the positioning icon and select the address you want to set.

How to modify the greeting content for boss direct recruitment How to modify the greeting content for boss direct recruitment Mar 01, 2024 pm 03:40 PM

In the job recruitment software called Boss Direct Jobs, users can personalize their greetings to better demonstrate their personality and job search intentions. However, sometimes the default greeting terms are rather mechanical and rigid. Many users want to make their own changes but don’t know where to set them. So this tutorial guide will introduce the detailed modification steps for players who want to know more. Come and follow this article to find out! How to change the answer when a boss directly hires someone to say hello: [Boss directly hires]-[My]-[Settings Icon]-[Greeting Language]. Specific steps: 1. First, we click on the boss direct recruitment software. After entering the homepage, we click [My] in the lower right corner; 2. Then when we come to the My page, we can see the relevant data.

Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Jun 12, 2024 pm 08:38 PM

Since the launch of ChatGLM-6B on March 14, 2023, the GLM series models have received widespread attention and recognition. Especially after ChatGLM3-6B was open sourced, developers are full of expectations for the fourth-generation model launched by Zhipu AI. This expectation has finally been fully satisfied with the release of GLM-4-9B. The birth of GLM-4-9B In order to give small models (10B and below) more powerful capabilities, the GLM technical team launched this new fourth-generation GLM series open source model: GLM-4-9B after nearly half a year of exploration. This model greatly compresses the model size while ensuring accuracy, and has faster inference speed and higher efficiency. The GLM technical team’s exploration has not

See all articles