Search code examples
phpemailimap

How to limit result on php-imap


I'm getting my mails from php-imap using php-imap-client, the script work without problems but i want to limit the number of mails to get from the server.

This is the script:

<?PHP

require_once "Imap.php";

$mailbox = 'imap-mail.outlook.com';
$username = '[email protected]';
$password = 'MYPASSWORD';
$encryption = 'ssl'; // or ssl or ''

// open connection
$imap = new Imap($mailbox, $username, $password, $encryption);

// stop on error
if($imap->isConnected()===false)
    die($imap->getError());

// get all folders as array of strings
$folders = $imap->getFolders();
foreach($folders as $folder)
    echo $folder;

// select folder Inbox
$imap->selectFolder('INBOX');

// count messages in current folder
$overallMessages = $imap->countMessages();
$unreadMessages = $imap->countUnreadMessages();

// fetch all messages in the current folder
$emails = $imap->getMessages($withbody = false);
var_dump($emails);

// add new folder for archive
$imap->addFolder('archive');

// move the first email to archive
$imap->moveMessage($emails[0]['id'], 'archive');

// delete second message
$imap->deleteMessage($emails[1]['id']);

The script i'm using: https://github.com/SSilence/php-imap-client

How can i do it?


Solution

  • Looking at the descriptions, the functions do not seem to have a way to limit the number of messages collected since they use the ID of the message and not just a general count. For this reason, you may have a varied list of IDs. Take their example dump, you have ID 15 and ID 14. The next one in the list could be ID 10 as the user may have deleted 13, 12, and 11.

    So you can collect the initial list, and then iterate over it with $imap->getMessage($id); It would look something like this:

    $overallMessages = $imap->countMessages();
    $unreadMessages = $imap->countUnreadMessages();
    
    $limitCount = 20;
    $partialEmailIdList = array();
    
    // fetch all messages in the current folder
    $emails = $imap->getMessages($withbody = false);
    
    if($limitCount < $overallMessages){
        for($i=0; $i<$limitCount; $++){
            // Populate array with IDs
            $partialEmailIdList[] = $emails[$i]['id'];
        }
    } else {
        foreach($emails as $email){
            $partialEmailIdList[] = $email['id'];
        }
    }
    foreach($partialEmailIdList as $mid){
            $message = $imap->getMessage($mid);
            // Do stuff...
    }