Sample code for 30+ languages & platforms
Unicode C++

Get IMAP Message Threads as JSON

See more IMAP Examples

Demonstrates the Chilkat Imap.QueryThread method, which sends the IMAP THREAD command for the selected mailbox and returns the thread hierarchy as JSON. The first argument is the threading algorithm (commonly REFERENCES or ORDEREDSUBJECT), the second is IMAP search criteria, and the third (bUid) selects UID vs sequence-number identifiers. The returned JSON has a top-level threads array whose nested arrays encode parent/child relationships. This example threads all messages in the Inbox.

Tip: JSON parsing code for this result can be generated at Chilkat Tools.

Background: "Conversation view" in a mail client — grouping a message with its replies and follow-ups — is exactly what the IMAP THREAD extension provides, computed on the server. REFERENCES threads by the References/In-Reply-To headers (the accurate way), while ORDEREDSUBJECT groups by subject. Not all servers support THREAD, so check HasCapability for it first.

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkImapW.h>
#include <CkJsonObjectW.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Demonstrates the Imap.QueryThread method, which sends the IMAP THREAD command for the
    //  selected mailbox and returns the thread hierarchy as JSON.  The 1st argument is the
    //  threading algorithm (such as REFERENCES or ORDEREDSUBJECT), the 2nd is IMAP search
    //  criteria, and the 3rd (bUid) selects UID vs sequence-number identifiers.

    CkImapW imap;

    imap.put_Ssl(true);
    imap.put_Port(993);

    success = imap.Connect(L"imap.example.com");
    if (success == false) {
        wprintf(L"%s\n",imap.lastErrorText());
        return;
    }

    success = imap.Login(L"user@example.com",L"myPassword");
    if (success == false) {
        wprintf(L"%s\n",imap.lastErrorText());
        return;
    }

    success = imap.SelectMailbox(L"Inbox");
    if (success == false) {
        wprintf(L"%s\n",imap.lastErrorText());
        return;
    }

    //  Group all messages into threads using the REFERENCES algorithm, returning UIDs.
    CkJsonObjectW json;
    success = imap.QueryThread(L"REFERENCES",L"ALL",true,json);
    if (success == false) {
        wprintf(L"%s\n",imap.lastErrorText());
        return;
    }

    json.put_EmitCompact(false);
    wprintf(L"%s\n",json.emit());

    //  JSON parsing code for this result can be generated at Chilkat's online tool:
    //  https://tools.chilkat.io/jsonParse

    success = imap.Disconnect();
    if (success == false) {
        wprintf(L"%s\n",imap.lastErrorText());
        return;
    }
    }