Sample code for 30+ languages & platforms
PureBasic

Search an IMAP Mailbox

See more IMAP Examples

Demonstrates the Chilkat Imap.QueryMbx method, which searches the selected mailbox using IMAP search criteria and stores the matching message identifiers in a MessageSet. If bUid is true, the identifiers are UIDs; otherwise they are sequence numbers. This example finds unseen messages and lists their UIDs.

Background: IMAP search runs on the server, so you can find matching messages without downloading them. The criteria string is standard IMAP search syntax — for example UNSEEN, FROM "alice@example.com", SUBJECT "invoice", or SINCE 1-Jan-2026 — and terms can be combined. The result is a MessageSet of identifiers you then fetch, flag, copy, or move. Requesting UIDs (bUid = true) is preferred because UIDs remain valid across sessions.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkImap.pb"
IncludeFile "CkMessageSet.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Demonstrates the Imap.QueryMbx method, which searches the selected mailbox using IMAP
    ;  search criteria and stores the matching message identifiers in a MessageSet.  If bUid is
    ;  1, the identifiers are UIDs; otherwise they are sequence numbers.

    imap.i = CkImap::ckCreate()
    If imap.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkImap::setCkSsl(imap, 1)
    CkImap::setCkPort(imap, 993)

    success = CkImap::ckConnect(imap,"imap.example.com")
    If success = 0
        Debug CkImap::ckLastErrorText(imap)
        CkImap::ckDispose(imap)
        ProcedureReturn
    EndIf

    success = CkImap::ckLogin(imap,"user@example.com","myPassword")
    If success = 0
        Debug CkImap::ckLastErrorText(imap)
        CkImap::ckDispose(imap)
        ProcedureReturn
    EndIf

    success = CkImap::ckSelectMailbox(imap,"Inbox")
    If success = 0
        Debug CkImap::ckLastErrorText(imap)
        CkImap::ckDispose(imap)
        ProcedureReturn
    EndIf

    ;  Search for unseen (unread) messages, returning their UIDs.
    msgSet.i = CkMessageSet::ckCreate()
    If msgSet.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkImap::ckQueryMbx(imap,"UNSEEN",1,msgSet)
    If success = 0
        Debug CkImap::ckLastErrorText(imap)
        CkImap::ckDispose(imap)
        CkMessageSet::ckDispose(msgSet)
        ProcedureReturn
    EndIf

    ;  Iterate the matching message identifiers.
    n.i = CkMessageSet::ckCount(msgSet)
    Debug "Matching messages: " + Str(n)
    i.i
    For i = 0 To n - 1
        Debug "UID: " + Str(CkMessageSet::ckGetId(msgSet,i))
    Next

    success = CkImap::ckDisconnect(imap)
    If success = 0
        Debug CkImap::ckLastErrorText(imap)
        CkImap::ckDispose(imap)
        CkMessageSet::ckDispose(msgSet)
        ProcedureReturn
    EndIf



    CkImap::ckDispose(imap)
    CkMessageSet::ckDispose(msgSet)


    ProcedureReturn
EndProcedure