PHP - imap_search() 函式



PHP 的 IMAP 函式幫助您訪問電子郵件帳戶,IMAP 代表 **I**nternet **M**ail **A**ccess **P**rotocol,使用這些函式您還可以處理 NNTP、POP3 協議和本地郵箱訪問方法。

imap_search() 函式接受表示 IMAP 流的資源值和表示搜尋條件的字串值作為引數,搜尋郵箱並以陣列的形式返回匹配的訊息。

語法

imap_search($imap_stream, $criteria, [$options, $charset]);

引數

序號 引數和描述
1

imap_stream (必需)

這是一個字串值,表示 IMAP 流,是 imap_open() 函式的返回值。

2

criteria (必需)

這是一個字串值,表示搜尋條件。

3

options (可選)

這是一個字串值,表示可選值 SE_UID。設定後,返回的陣列包含 UID 而不是訊息序列。

4

$charset (可選)

這是一個字串值,表示搜尋期間使用的 MIME 字元集。

返回值

如果成功,此函式返回一個包含訊息編號/UID 的陣列,這些編號/UID 代表匹配的訊息;如果失敗,則返回布林值 FALSE。

PHP 版本

此函式首次在 PHP 4 版本中引入,並在所有後續版本中均有效。

示例

以下是此函式的另一個示例:

<html>
   <body>
      <?php
         //Establishing connection
         $url = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX";
         $id = "tutorialspoint.test@gmail.com";
         $pwd = "cohondob_123";
         $imap = imap_open($url, $id, $pwd);
         print("Connection established...."."<br>");
         print("Results of the search: "."<br>");
         
         $emailData = imap_search($imap, '');
         print_r($emailData);
	    
         //Closing the connection
         imap_close($imap);   
      ?>
   </body>
</html>

這將生成以下輸出:

Connection established....
Results of the search:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )

示例

以下是此函式的另一個示例;這將讀取當前收件箱中未讀的訊息:

<html>
   <body>
      <?php
         //Establishing connection
         $url = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX";
         $id = "tutorialspoint.test@gmail.com";
         $pwd = "cohondob_123";
         $imap = imap_open($url, $id, $pwd);
         print("Connection established...."."<br>");
         print("Contents of the matched messages: "."<br>");
         $emailData = imap_search($imap, "UNSEEN");
         foreach ($emailData as $msg) {
            $msg = imap_fetchbody($imap, $msg, "1");
            print(quoted_printable_decode($msg)."<br>");                
         }    
         //Closing the connection
         imap_close($imap);   
      ?>
   </body>
</html>

輸出

這將生成以下輸出:

Connection established....
Contents of the matched messages:
Array ( [0] => 4 [1] => 5 [2] => 6 )
#sample_mail4
#sample_mail5
#sample_mail6

示例

以下是使用可選引數的此函式示例:

<html>
   <body>
      <?php
         //Establishing connection
         $url = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX";
         $id = "tutorialspoint.test@gmail.com";
         $pwd = "cohondob_123";
         $imap = imap_open($url, $id, $pwd);
         print("Connection established...."."<br>");
         print("Contents  of the matched messages: "."<br>");
         $data = imap_search($imap, "ALL", SE_UID);
         print_r($data);
    
         //Closing the connection
         imap_close($imap);   
      ?>
   </body>
</html>

輸出

這將生成以下輸出:

Connection established....
Contents of the matched messages:
Array ( 
   [0] => 19 
   [1] => 20 
   [2] => 42 
   [3] => 49 
   [4] => 50 
   [5] => 51 
)
php_function_reference.htm
廣告
© . All rights reserved.