Tcl
Tcl
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 Tcl Downloads
load ./chilkat.dll
set success 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.
set imap [new_CkImap]
CkImap_put_Ssl $imap 1
CkImap_put_Port $imap 993
set success [CkImap_Connect $imap "imap.example.com"]
if {$success == 0} then {
puts [CkImap_lastErrorText $imap]
delete_CkImap $imap
exit
}
set success [CkImap_Login $imap "user@example.com" "myPassword"]
if {$success == 0} then {
puts [CkImap_lastErrorText $imap]
delete_CkImap $imap
exit
}
set success [CkImap_SelectMailbox $imap "Inbox"]
if {$success == 0} then {
puts [CkImap_lastErrorText $imap]
delete_CkImap $imap
exit
}
# Search for unseen (unread) messages, returning their UIDs.
set msgSet [new_CkMessageSet]
set success [CkImap_QueryMbx $imap "UNSEEN" 1 $msgSet]
if {$success == 0} then {
puts [CkImap_lastErrorText $imap]
delete_CkImap $imap
delete_CkMessageSet $msgSet
exit
}
# Iterate the matching message identifiers.
set n [CkMessageSet_get_Count $msgSet]
puts "Matching messages: $n"
for {set i 0} {$i <= [expr $n - 1]} {incr i} {
puts "UID: [CkMessageSet_GetId $msgSet $i]"
}
set success [CkImap_Disconnect $imap]
if {$success == 0} then {
puts [CkImap_lastErrorText $imap]
delete_CkImap $imap
delete_CkMessageSet $msgSet
exit
}
delete_CkImap $imap
delete_CkMessageSet $msgSet