Sample code for 30+ languages & platforms
Unicode C

Sorting Email

Demonstrates how to sort an email bundle.

Chilkat Unicode C Downloads

Unicode C
#include <C_CkImapW.h>
#include <C_CkMessageSetW.h>
#include <C_CkEmailBundleW.h>
#include <C_CkEmailW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkImapW imap;
    BOOL fetchUids;
    HCkMessageSetW messageSet;
    HCkEmailBundleW bundle;
    BOOL headersOnly;
    BOOL ascending;
    HCkEmailW email;
    int i;

    success = FALSE;

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

    imap = CkImapW_Create();

    // Connect to the IMAP server.
    // Use TLS
    CkImapW_putSsl(imap,TRUE);
    CkImapW_putPort(imap,993);
    success = CkImapW_Connect(imap,L"imap.example.com");
    if (success == FALSE) {
        wprintf(L"%s\n",CkImapW_lastErrorText(imap));
        CkImapW_Dispose(imap);
        return;
    }

    // Login
    success = CkImapW_Login(imap,L"myLogin",L"myPassword");
    if (success == FALSE) {
        wprintf(L"%s\n",CkImapW_lastErrorText(imap));
        CkImapW_Dispose(imap);
        return;
    }

    // Select an IMAP mailbox
    success = CkImapW_SelectMailbox(imap,L"Inbox");
    if (success == FALSE) {
        wprintf(L"%s\n",CkImapW_lastErrorText(imap));
        CkImapW_Dispose(imap);
        return;
    }

    fetchUids = TRUE;
    messageSet = CkMessageSetW_Create();
    success = CkImapW_QueryMbx(imap,L"ALL",fetchUids,messageSet);
    if (success == FALSE) {
        wprintf(L"%s\n",CkImapW_lastErrorText(imap));
        CkImapW_Dispose(imap);
        CkMessageSetW_Dispose(messageSet);
        return;
    }

    // Fetch the email headers into a bundle object:
    bundle = CkEmailBundleW_Create();
    headersOnly = TRUE;
    success = CkImapW_FetchMsgSet(imap,headersOnly,messageSet,bundle);
    if (success == FALSE) {
        wprintf(L"%s\n",CkImapW_lastErrorText(imap));
        CkImapW_Dispose(imap);
        CkMessageSetW_Dispose(messageSet);
        CkEmailBundleW_Dispose(bundle);
        return;
    }

    // Sort the email bundle by date, recipient, sender, or subject:
    ascending = TRUE;
    CkEmailBundleW_SortByDate(bundle,ascending);

    // To sort by recipient, sender, or subject, call 
    // SortBySender, SortByRecipient, or SortBySubject.

    // Display the Subject and From of each email.
    email = CkEmailW_Create();
    i = 0;
    while (i < CkEmailBundleW_getMessageCount(bundle)) {
        CkEmailBundleW_EmailAt(bundle,i,email);

        wprintf(L"%s\n",CkEmailW_getHeaderField(email,L"Date"));
        wprintf(L"%s\n",CkEmailW_subject(email));
        wprintf(L"%s\n",CkEmailW_ck_from(email));
        wprintf(L"--\n");

        i = i + 1;
    }

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


    CkImapW_Dispose(imap);
    CkMessageSetW_Dispose(messageSet);
    CkEmailBundleW_Dispose(bundle);
    CkEmailW_Dispose(email);

    }