Sample code for 30+ languages & platforms
Lianja

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

Lianja
llSuccess = .F.

//  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
//  .T., the identifiers are UIDs; otherwise they are sequence numbers.

loImap = createobject("CkImap")

loImap.Ssl = .T.
loImap.Port = 993

llSuccess = loImap.Connect("imap.example.com")
if (llSuccess = .F.) then
    ? loImap.LastErrorText
    release loImap
    return
endif

llSuccess = loImap.Login("user@example.com","myPassword")
if (llSuccess = .F.) then
    ? loImap.LastErrorText
    release loImap
    return
endif

llSuccess = loImap.SelectMailbox("Inbox")
if (llSuccess = .F.) then
    ? loImap.LastErrorText
    release loImap
    return
endif

//  Search for unseen (unread) messages, returning their UIDs.
loMsgSet = createobject("CkMessageSet")
llSuccess = loImap.QueryMbx("UNSEEN",.T.,loMsgSet)
if (llSuccess = .F.) then
    ? loImap.LastErrorText
    release loImap
    release loMsgSet
    return
endif

//  Iterate the matching message identifiers.
n = loMsgSet.Count
? "Matching messages: " + str(n)

for i = 0 to n - 1
    ? "UID: " + str(loMsgSet.GetId(i))
next

llSuccess = loImap.Disconnect()
if (llSuccess = .F.) then
    ? loImap.LastErrorText
    release loImap
    release loMsgSet
    return
endif



release loImap
release loMsgSet