Sample code for 30+ languages & platforms
Delphi DLL

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 Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
imap: HCkImap;
json: HCkJsonObject;

begin
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.

imap := CkImap_Create();

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

success := CkImap_Connect(imap,'imap.example.com');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;
success := CkImap_Login(imap,'user@example.com','myPassword');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

success := CkImap_SelectMailbox(imap,'Inbox');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

//  Group all messages into threads using the REFERENCES algorithm, returning UIDs.
json := CkJsonObject_Create();
success := CkImap_QueryThread(imap,'REFERENCES','ALL',True,json);
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

CkJsonObject_putEmitCompact(json,False);
Memo1.Lines.Add(CkJsonObject__emit(json));

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

success := CkImap_Disconnect(imap);
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imap));
    Exit;
  end;

CkImap_Dispose(imap);
CkJsonObject_Dispose(json);