邮件接收类

Jun 06, 2016 pm 07:31 PM
コード 改訂 現れる 引き継ぐ 自分の 郵便

根据网上找到的代码自己修改了一点。 添加了所有编码统一转换为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;
		}
	}     
}
 
?>
ログイン後にコピー
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Windows 11のコントロールパネルからOutlookメールが失われる Windows 11のコントロールパネルからOutlookメールが失われる Feb 29, 2024 pm 03:16 PM

Windows 11 のコントロール パネルに Outlook メール アイコンがありませんか?この予期せぬ状況は、通信ニーズに OutlookMail に依存している一部の人々に混乱と懸念を引き起こしました。 Outlook メールがコントロール パネルに表示されないのはなぜですか?コントロール パネルに Outlook メール アイコンが表示されない理由はいくつか考えられます。 Outlook が正しくインストールされていません。 Microsoft Store から Office アプリケーションをインストールしても、メール アプレットはコントロール パネルに追加されません。コントロール パネルに mlcfg32.cpl ファイルの場所がありません。レジストリ内のmlcfg32.cplファイルへのパスが正しくありません。現在、オペレーティング システムはこのアプリケーションを実行するように構成されていません

DingTalk のグループ内の個人名を変更する方法_DingTalk のグループ内の個人名を変更する方法 DingTalk のグループ内の個人名を変更する方法_DingTalk のグループ内の個人名を変更する方法 Mar 29, 2024 pm 08:41 PM

1. まずDingTalkを開きます。 2. グループ チャットを開き、右上隅にある 3 つの点をクリックします。 3. このグループで私のニックネームを見つけます。 4. クリックして入力し、変更して保存します。

Douyin Blue V の名前は変更できますか?法人Douyin Blue Vアカウントの名前を変更する手順は何ですか? Douyin Blue V の名前は変更できますか?法人Douyin Blue Vアカウントの名前を変更する手順は何ですか? Mar 22, 2024 pm 12:51 PM

Douyin Blue V 認証は、Douyin プラットフォーム上の企業またはブランドの公式認証であり、ブランド イメージと信頼性の向上に役立ちます。企業の発展戦略の調整やブランドイメージの更新に伴い、企業はDouyin Blue V認証の名称を変更したい場合があります。では、Douyin Blue V は名前を変更できるのでしょうか?答えは「はい」です。この記事では、エンタープライズ Douyin Blue V アカウントの名前を変更する手順を詳しく紹介します。 1.Douyin Blue V の名前は変更できますか? Douyin Blue V アカウントの名前は変更できます。 Douyin の公式規定によると、企業の Blue V 認定アカウントは、一定の条件を満たした後にアカウント名の変更を申請できます。一般的に、企業は社名変更の合法性と必要性​​を証明するために、営業許可証、組織コード証明書などの関連資料を提供する必要があります。 2. 企業のDouyin Blue Vアカウントの名前を変更する手順は何ですか?

あらゆるデバイス上の GE ユニバーサル リモート コード プログラム あらゆるデバイス上の GE ユニバーサル リモート コード プログラム Mar 02, 2024 pm 01:58 PM

デバイスをリモートでプログラムする必要がある場合は、この記事が役に立ちます。あらゆるデバイスをプログラミングするためのトップ GE ユニバーサル リモート コードを共有します。 GE リモコンとは何ですか? GEUniversalRemote は、スマート TV、LG、Vizio、Sony、Blu-ray、DVD、DVR、Roku、AppleTV、ストリーミング メディア プレーヤーなどの複数のデバイスを制御するために使用できるリモコンです。 GEUniversal リモコンには、さまざまな機能を備えたさまざまなモデルがあります。 GEUniversalRemote は最大 4 台のデバイスを制御できます。あらゆるデバイスでプログラムできるトップのユニバーサル リモート コード GE リモコンには、さまざまなデバイスで動作できるようにするコードのセットが付属しています。してもいいです

Win10のスリープ時間変更のヒントが明らかに Win10のスリープ時間変更のヒントが明らかに Mar 08, 2024 pm 06:39 PM

Win10 のスリープ時間変更のヒントが明らかに 現在広く使用されているオペレーティング システムの 1 つである Windows 10 には、ユーザーがコンピューターを使用していないときに電力を節約し、画面を保護するのに役立つスリープ機能があります。ただし、デフォルトのスリープ時間がユーザーのニーズを満たさない場合があるため、Win10 のスリープ時間を変更する方法を知ることが特に重要です。この記事では、Win10 のスリープ時間を変更するためのヒントを紹介します。これにより、システムのスリープ設定を簡単にカスタマイズできるようになります。 1.「設定」からWin10のスリープ時間を変更します。まず、最も簡単な修正です。

Copilot を使用してコードを生成する方法 Copilot を使用してコードを生成する方法 Mar 23, 2024 am 10:41 AM

プログラマーとして、私はコーディング体験を簡素化するツールに興奮しています。人工知能ツールの助けを借りて、デモ コードを生成し、要件に応じて必要な変更を加えることができます。 Visual Studio Code に新しく導入された Copilot ツールを使用すると、自然言語によるチャット対話を備えた AI 生成コードを作成できます。機能を説明することで、既存のコードの意味をより深く理解できます。 Copilot を使用してコードを生成するにはどうすればよいですか?始めるには、まず最新の PowerPlatformTools 拡張機能を入手する必要があります。これを実現するには、拡張機能のページに移動し、「PowerPlatformTool」を検索して、[インストール] ボタンをクリックする必要があります。

Xianyuで公開されている製品のアドレスの場所を変更する方法 Xianyuで公開されている製品のアドレスの場所を変更する方法 Mar 28, 2024 pm 03:36 PM

Xianyuプラットフォームで製品を公開する際、ユーザーは実際の状況に応じて製品の地理的位置情報をカスタマイズできるため、潜在的な購入者は製品の特定の位置をより正確に把握できます。製品が無事に店頭に並べられれば、販売者の所在地が変わっても心配する必要はありません。 Xianyu プラットフォームは、柔軟で便利な変更機能を提供しています。公開された製品のアドレスを変更したい場合、どのように変更すればよいでしょうか? このチュートリアル ガイドでは、詳細なステップバイステップ ガイドが提供されます。助けてください、皆さん! Xianyu でリリース製品アドレスを変更するにはどうすればよいですか? 1. Xianyu を開き、公開したものをクリックして製品を選択し、[編集] をクリックします。 2. 位置決めアイコンをクリックし、設定したいアドレスを選択します。

Linux の「.a」ファイルを作成して実行する Linux の「.a」ファイルを作成して実行する Mar 20, 2024 pm 04:46 PM

Linux オペレーティング システムでファイルを操作するには、開発者がファイル、コード、プログラム、スクリプトなどを効率的に作成および実行できるようにするさまざまなコマンドとテクニックを使用する必要があります。 Linux 環境では、拡張子「.a」を持つファイルは静的ライブラリとして非常に重要です。これらのライブラリはソフトウェア開発において重要な役割を果たし、開発者が複数のプログラム間で共通の機能を効率的に管理および共有できるようにします。 Linux 環境で効果的なソフトウェア開発を行うには、「.a」ファイルの作成方法と実行方法を理解することが重要です。この記事では、Linux の「.a」ファイルのインストールと構成方法を包括的に紹介します。Linux の「.a」ファイルの定義、目的、構造、作成および実行方法について見てみましょう。 Lとは何ですか

See all articles