Sample code for 30+ languages & platforms
PowerBuilder

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 PowerBuilder Downloads

PowerBuilder
integer li_rc
integer li_Success
oleobject loo_Imap
oleobject loo_Json

li_Success = 0

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

loo_Imap = create oleobject
li_rc = loo_Imap.ConnectToNewObject("Chilkat.Imap")
if li_rc < 0 then
    destroy loo_Imap
    MessageBox("Error","Connecting to COM object failed")
    return
end if

loo_Imap.Ssl = 1
loo_Imap.Port = 993

li_Success = loo_Imap.Connect("imap.example.com")
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    return
end if

li_Success = loo_Imap.Login("user@example.com","myPassword")
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    return
end if

li_Success = loo_Imap.SelectMailbox("Inbox")
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    return
end if

//  Group all messages into threads using the REFERENCES algorithm, returning UIDs.
loo_Json = create oleobject
li_rc = loo_Json.ConnectToNewObject("Chilkat.JsonObject")

li_Success = loo_Imap.QueryThread("REFERENCES","ALL",1,loo_Json)
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    destroy loo_Json
    return
end if

loo_Json.EmitCompact = 0
Write-Debug loo_Json.Emit()

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

li_Success = loo_Imap.Disconnect()
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    destroy loo_Json
    return
end if



destroy loo_Imap
destroy loo_Json