2010-09-29 49 views
2

我使用內置IMAP函數的PHP來構建一個基本的webmail客戶端(主要用於訪問Gmail帳戶)。我目前在郵箱列表視圖中打開了一個路障,我在該郵箱中顯示按日期(升序或降序)排序的分頁列表。PHP IMAP庫 - 從郵箱中檢索有限的郵件列表

我最初的實現是通過imap_headers()從郵箱中檢索所有消息,並根據日期對該數組進行排序,然後返回與用戶想要查看的列表的當前頁面對應的數組段。對於郵件數量較少的郵箱,這種方式可以正常工作,但隨着郵箱大小的增加(對於郵箱數量大約爲600條,執行時間平均大約爲10秒),性能大大降低。而對於這個客戶端的一些用戶來說,600個郵件對於一個郵箱來說只是一個小數字,在他們的收件箱中有一些容易發送5到10萬條消息。

所以我第二次解決問題的方法是不是檢索郵箱中所有郵件的標題,而是使用imap_num_msg()獲得郵件總數,並使用該數字構建for循環,其中循環計數器用作消息號碼。對於每次迭代,我都使用該消息號調用imap_headerinfo()。

這樣做效果更好,但我的印象是消息編號直接對應於收到消息的時間,所以消息沒有。 1是最舊的消息,imap_num_msg()返回的數字是最新消息的消息編號。因此,我仍然可以在分頁列表中按日期提供排序。但經過測試,似乎消息編號與收到日期不符,實際上我不知道它們是如何分配的。

任何幫助或方向將不勝感激。

回答

1

我一直在玩這個,這裏是一些即時消息的剪輯,分頁工作很好,每頁只能獲得幾封郵件。我不會粘貼所有的代碼,只是主要部分。希望這有助於:)

// main method to get the mails __getFormattedBasics() just calls imap_hearderinfo() loop runs backwards by default to get newest first 
private function __getMails($Model, $query) { 
      $pagination = $this->_figurePagination($query); 

      $mails = array(); 
      for ($i = $pagination['start']; $i > $pagination['end']; $i--) { 
       $mails[] = $this->__getFormattedBasics($Model, $i); 
      } 

      unset($mail); 

      return $mails; 
     } 

// this just uses the current page number, limit per page and figures the start/end for the loop above you can sort in the other direction passing asc/desc 
protected function _figurePagination($query) { 
      $count = $this->_mailCount($query); // total mails 
      $pages = ceil($count/$query['limit']); // total pages 
      $query['page'] = $query['page'] <= $pages ? $query['page'] : $pages; // dont let the page be more than available pages 

      $return = array(
       'start' => $query['page'] == 1 
        ? $count // start at the end 
        : ($pages - $query['page'] + 1) * $query['limit'], // start at the end - x pages 
      ); 

      $return['end'] = $query['limit'] >= $count 
       ? 0 
       : $return['start'] - $query['limit']; 

      $return['end'] = $return['end'] >= 0 ? $return['end'] : 0; 

      if (isset($query['order']['date']) && $query['order']['date'] == 'asc') { 
       return array(
        'start' => $return['end'], 
        'end' => $return['start'], 
       ); 
      } 

      return $return; 
     } 

    private function __getFormattedBasics($Model, $message_id) { 
     $mail = imap_headerinfo($this->MailServer, $message_id); 
     $structure = imap_fetchstructure($this->MailServer, $mail->Msgno); 

     $toName = isset($mail->to[0]->personal) ? $mail->to[0]->personal : $mail->to[0]->mailbox; 
     $fromName = isset($mail->from[0]->personal) ? $mail->from[0]->personal : $mail->from[0]->mailbox; 
     $replyToName = isset($mail->reply_to[0]->personal) ? $mail->reply_to[0]->personal : $mail->reply_to[0]->mailbox; 

....