简体   繁体   中英

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

I want to get the recent last 1 email from inbox using IMAP in php. Please help me. I don't know how to get the last email from inbox. Please guide me with it. I will be thanks for your guideline.

Here is my code

              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 = '';
                }

Using the imap_search function, there is no option to specify the number of entries that should be returned.

In your code, you are using

foreach($emails as $mail) {

The most simple solution here, would be only using the first element of the array, which would represent the most recent message meeting the search criteria.

$mail = $emails[0];

edit

I guess the array is in reverse order, so get the last element instead of the first - using end .

$mail = end($emails);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM