Tcl
Tcl
Fetch a Range of IMAP Messages by Sequence Number
See more IMAP Examples
Demonstrates the Chilkat Imap.FetchRange method, which downloads a contiguous run of messages by sequence number. The arguments are headersOnly, the starting sequence number, the count of messages, and the EmailBundle that receives them. This example uses the message count returned by SelectMailbox to fetch the headers of the 10 most recent messages.
Background: IMAP sequence numbers are 1-based positions within the selected mailbox, from 1 (oldest) to the message count (newest), and they shift whenever messages are expunged. That makes
FetchRange ideal for "give me the newest N" style paging within a single session, but note that sequence numbers are not stable identifiers across sessions the way UIDs are — use a UID-based approach if you need to remember which messages you have already seen.Chilkat Tcl Downloads
load ./chilkat.dll
set success 0
# Demonstrates the Imap.FetchRange method, which downloads a contiguous run of messages by
# sequence number. The 1st argument is headersOnly, the 2nd is the starting sequence number,
# the 3rd is the count of messages, and the 4th is the EmailBundle that receives them.
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
}
# SelectMailbox returns the number of messages in the mailbox, or -1 on failure.
set numMessages [CkImap_SelectMailbox $imap "Inbox"]
if {$numMessages < 0} then {
puts [CkImap_lastErrorText $imap]
delete_CkImap $imap
exit
}
# Download the 10 most recent messages (headers only).
set startSeqnum [expr $numMessages - 9]
if {$startSeqnum < 1} then {
set startSeqnum 1
}
set bundle [new_CkEmailBundle]
set success [CkImap_FetchRange $imap 1 $startSeqnum 10 $bundle]
if {$success == 0} then {
puts [CkImap_lastErrorText $imap]
delete_CkImap $imap
delete_CkEmailBundle $bundle
exit
}
set n [CkEmailBundle_get_MessageCount $bundle]
puts "Fetched $n message headers."
set success [CkImap_Disconnect $imap]
if {$success == 0} then {
puts [CkImap_lastErrorText $imap]
delete_CkImap $imap
delete_CkEmailBundle $bundle
exit
}
delete_CkImap $imap
delete_CkEmailBundle $bundle