Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.0.0+

Download Unread Email from IMAP Mailbox

Download unread email messages from an IMAP mailbox.

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\Email;
use Chilkat2\EmailBundle;
use Chilkat2\Imap;
use Chilkat2\MessageSet;

// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

$imap = new Imap();

// Connect to an IMAP server.
// Use TLS
$imap->Ssl = true;
$imap->Port = 993;
try {
    $imap->Connect('imap.example.com');

    // Login
    $imap->Login('admin@chilkatsoft.com', 'myPassword');

    // Select an IMAP mailbox
    $imap->SelectMailbox('Inbox');

    // Find emails marked as seen or not already seen:
    $seenSearch = 'SEEN';
    $notSeenSearch = 'NOT SEEN';

    // Get the set of unseen message UIDs
    $fetchUids = true;
    $messageSet = new MessageSet();
    $imap->QueryMbx($notSeenSearch, $fetchUids, $messageSet);

    // Fetch the unseen emails into a bundle object:
    $bundle = new EmailBundle();
    $headersOnly = false;
    $imap->FetchMsgSet($headersOnly, $messageSet, $bundle);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Display the Subject and From of each email.
$email = new Email();
$i = 0;
$numEmails = $bundle->MessageCount;
while ($i < $numEmails) {
    $bundle->EmailAt($i, $email);

    echo $email->GetHeaderField('Date'), "\n";
    echo $email->Subject, "\n";
    echo $email->From, "\n";
    echo "--\n";
    $i = $i + 1;
}

// Disconnect from the IMAP server.
$imap->Disconnect();