Sample code for 30+ languages & platforms
C

Search an IMAP Mailbox

See more IMAP Examples

Demonstrates the Chilkat Imap.QueryMbx method, which searches the selected mailbox using IMAP search criteria and stores the matching message identifiers in a MessageSet. If bUid is true, the identifiers are UIDs; otherwise they are sequence numbers. This example finds unseen messages and lists their UIDs.

Background: IMAP search runs on the server, so you can find matching messages without downloading them. The criteria string is standard IMAP search syntax — for example UNSEEN, FROM "alice@example.com", SUBJECT "invoice", or SINCE 1-Jan-2026 — and terms can be combined. The result is a MessageSet of identifiers you then fetch, flag, copy, or move. Requesting UIDs (bUid = true) is preferred because UIDs remain valid across sessions.

Chilkat C Downloads

C
#include <C_CkImap.h>
#include <C_CkMessageSet.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkImap imap;
    HCkMessageSet msgSet;
    int n;
    int i;

    success = FALSE;

    //  Demonstrates the Imap.QueryMbx method, which searches the selected mailbox using IMAP
    //  search criteria and stores the matching message identifiers in a MessageSet.  If bUid is
    //  TRUE, the identifiers are UIDs; otherwise they are sequence numbers.

    imap = CkImap_Create();

    CkImap_putSsl(imap,TRUE);
    CkImap_putPort(imap,993);

    success = CkImap_Connect(imap,"imap.example.com");
    if (success == FALSE) {
        printf("%s\n",CkImap_lastErrorText(imap));
        CkImap_Dispose(imap);
        return;
    }

    success = CkImap_Login(imap,"user@example.com","myPassword");
    if (success == FALSE) {
        printf("%s\n",CkImap_lastErrorText(imap));
        CkImap_Dispose(imap);
        return;
    }

    success = CkImap_SelectMailbox(imap,"Inbox");
    if (success == FALSE) {
        printf("%s\n",CkImap_lastErrorText(imap));
        CkImap_Dispose(imap);
        return;
    }

    //  Search for unseen (unread) messages, returning their UIDs.
    msgSet = CkMessageSet_Create();
    success = CkImap_QueryMbx(imap,"UNSEEN",TRUE,msgSet);
    if (success == FALSE) {
        printf("%s\n",CkImap_lastErrorText(imap));
        CkImap_Dispose(imap);
        CkMessageSet_Dispose(msgSet);
        return;
    }

    //  Iterate the matching message identifiers.
    n = CkMessageSet_getCount(msgSet);
    printf("Matching messages: %d\n",n);

    for (i = 0; i <= n - 1; i++) {
        printf("UID: %u\n",CkMessageSet_GetId(msgSet,i));
    }

    success = CkImap_Disconnect(imap);
    if (success == FALSE) {
        printf("%s\n",CkImap_lastErrorText(imap));
        CkImap_Dispose(imap);
        CkMessageSet_Dispose(msgSet);
        return;
    }



    CkImap_Dispose(imap);
    CkMessageSet_Dispose(msgSet);

    }