Sample code for 30+ languages & platforms
Tcl

Fetch a MessageSet into an EmailBundle

See more IMAP Examples

Demonstrates the Chilkat Imap.FetchMsgSet method, which downloads the messages identified by a MessageSet and appends them to an EmailBundle. The arguments are headersOnly, the MessageSet, and the EmailBundle (which is not cleared). This example searches for unseen messages and downloads the whole set.

Background: This is the natural pairing with QueryMbx: search to get a MessageSet of matching identifiers, then download exactly those messages in one call. Fetching a set is far more efficient than looping one message at a time, and it returns an EmailBundle you iterate with MessageCount and EmailAt. Pass headersOnly = true to pull just headers for a fast preview list.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Demonstrates the Imap.FetchMsgSet method, which downloads the messages identified by a
#  MessageSet and appends them to an EmailBundle.  The 1st argument is headersOnly, the 2nd
#  is the MessageSet, and the 3rd is the EmailBundle (which is not cleared).

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
}

#  Find the messages to download (here, the unseen messages by UID).
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
}

#  Download the messages in the set (full bodies) into a bundle.
set bundle [new_CkEmailBundle]

set success [CkImap_FetchMsgSet $imap 0 $msgSet $bundle]
if {$success == 0} then {
    puts [CkImap_lastErrorText $imap]
    delete_CkImap $imap
    delete_CkMessageSet $msgSet
    delete_CkEmailBundle $bundle
    exit
}

set n [CkEmailBundle_get_MessageCount $bundle]
puts "Fetched $n messages."
set email [new_CkEmail]

for {set i 0} {$i <= [expr $n - 1]} {incr i} {
    set success [CkEmailBundle_EmailAt $bundle $i $email]
    puts [CkEmail_subject $email]
}

set success [CkImap_Disconnect $imap]
if {$success == 0} then {
    puts [CkImap_lastErrorText $imap]
    delete_CkImap $imap
    delete_CkMessageSet $msgSet
    delete_CkEmailBundle $bundle
    delete_CkEmail $email
    exit
}


delete_CkImap $imap
delete_CkMessageSet $msgSet
delete_CkEmailBundle $bundle
delete_CkEmail $email