Sample code for 30+ languages & platforms
C

Determine the Number of Unseen Email Messages

Demonstrates how to determine how many unseen messages exist in an email account on an IMAP server.

Chilkat C Downloads

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

void ChilkatSample(void)
    {
    BOOL success;
    HCkImap imap;
    int totalNum;
    BOOL fetchUids;
    HCkMessageSet messageSet;
    unsigned long numUnseen;
    int i;

    success = FALSE;

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

    imap = CkImap_Create();

    // Connect to an IMAP server.
    // Use TLS
    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;
    }

    // Login
    success = CkImap_Login(imap,"***","***");
    if (success == FALSE) {
        printf("%s\n",CkImap_lastErrorText(imap));
        CkImap_Dispose(imap);
        return;
    }

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

    // After selecting the mailbox. the total number of emails
    // is immediately available:
    totalNum = CkImap_getNumMessages(imap);
    printf("Num messages = %d\n",totalNum);

    // To determine the number of unseen messages, a call
    // to Search is required, which returns the set of UIDs
    // of all unseen messages.

    // We can choose to fetch UIDs or sequence numbers.
    fetchUids = TRUE;
    messageSet = CkMessageSet_Create();
    success = CkImap_QueryMbx(imap,"UNSEEN",fetchUids,messageSet);
    if (success == FALSE) {
        printf("%s\n",CkImap_lastErrorText(imap));
        CkImap_Dispose(imap);
        CkMessageSet_Dispose(messageSet);
        return;
    }

    numUnseen = CkMessageSet_getCount(messageSet);
    printf("%u\n",numUnseen);

    printf("UIDs ----\n");

    // Display the UIDs
    i = 0;
    while (i < CkMessageSet_getCount(messageSet)) {
        printf("%u\n",CkMessageSet_GetId(messageSet,i));
        i = i + 1;
    }

    // Disconnect from the IMAP server.
    success = CkImap_Disconnect(imap);


    CkImap_Dispose(imap);
    CkMessageSet_Dispose(messageSet);

    }