Sample code for 30+ languages & platforms
C

How to Download Messages in MessageSet One at a Time

See more IMAP Examples

If a message set contains a huge number of emails, it's NOT a good idea to try to download all at once into an email bundle using a method such as FetchBundle. It's better to iterate over the messages in the set to download one by one.

Chilkat C Downloads

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

void ChilkatSample(void)
    {
    BOOL success;
    HCkImap imap;
    BOOL fetchUids;
    HCkMessageSet messageSet;
    HCkEmail email;
    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 using 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;
    }

    // Authenticate
    success = CkImap_Login(imap,"email_account_login","email_account_password");
    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;
    }

    // Search for messages and return a set of matching messages.
    // (This example will simply search for ALL messages.)
    fetchUids = TRUE;

    messageSet = CkMessageSet_Create();
    success = CkImap_QueryMbx(imap,"ALL",fetchUids,messageSet);
    if (success == FALSE) {
        printf("%s\n",CkImap_lastErrorText(imap));
        CkImap_Dispose(imap);
        CkMessageSet_Dispose(messageSet);
        return;
    }

    printf("Number of messages = %d\n",CkMessageSet_getCount(messageSet));

    email = CkEmail_Create();
    i = 0;
    while (i < CkMessageSet_getCount(messageSet)) {
        success = CkImap_FetchEmail(imap,FALSE,CkMessageSet_GetId(messageSet,i),fetchUids,email);
        if (success == FALSE) {
            printf("%s\n",CkImap_lastErrorText(imap));
            CkImap_Dispose(imap);
            CkMessageSet_Dispose(messageSet);
            CkEmail_Dispose(email);
            return;
        }

        printf("%s; %s\n",CkEmail_ck_from(email),CkEmail_subject(email));

        i = i + 1;
    }

    printf("OK\n");


    CkImap_Dispose(imap);
    CkMessageSet_Dispose(messageSet);
    CkEmail_Dispose(email);

    }