簡體   English   中英

如何在PHP中使用IMAP從收件箱中獲取最近的最近1封電子郵件

[英]How to get recent last 1 email from inbox with IMAP in PHP

我想使用php中的IMAP從收件箱中獲取最近的最近1封電子郵件。 請幫我。 我不知道如何從收件箱中獲取最后一封電子郵件。 請指導我。 感謝您的指導。

這是我的代碼

              set_time_limit(4000); 

                // Connect to gmail
                    $hostname = '{imap.gmail.com:993/ssl/novalidate-cert}[Gmail]/All Mail';
                    $username = 'myemail@gmail.com';
                    $password = 'mypassword';
                    $keyword  = 'Delivery to the following recipient failed permanently';

                // try to connect 
                $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

                 $emails = imap_search($inbox,'BODY "'.$keyword.'"', SE_FREE, "UTF-8");
                $output = '';

                foreach($emails as $mail) {

                    $headerInfo = imap_headerinfo($inbox,$mail);

                    $output .= $headerInfo->subject.'<br/>';
                    $output .= $headerInfo->toaddress.'<br/>';
                    $output .= $headerInfo->date.'<br/>';
                    $output .= $headerInfo->fromaddress.'<br/>';
                    $output .= $headerInfo->reply_toaddress.'<br/>';

                    $emailStructure = imap_fetchstructure($inbox,$mail);

                    if(!isset($emailStructure->parts)) {
                         $output .= imap_body($inbox, $mail, FT_PEEK).'<br/></br/><br/>';

                    } else {
                        //    
                    }
                   echo $output;
                   $output = '';
                }

使用imap_search函數時,沒有任何選項可以指定應返回的條目數。

在您的代碼中,您正在使用

foreach($emails as $mail) {

這里最簡單的解決方案是僅使用數組的第一個元素,該元素表示滿足搜索條件的最新消息。

$mail = $emails[0];

編輯

我猜數組是相反的順序,所以得到最后一個元素而不是第一個使用end

$mail = end($emails);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM