Sample code for 30+ languages & platforms
Tcl Requires Chilkat v11.0.0+

How to Copy IMAP Mail to another IMAP Server

Demonstrates how to copy the entire contents of an IMAP mailbox to another IMAP server.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  This example requires the Chilkat API to have been previously unlocked.
#  See Global Unlock Sample for sample code.

set imapSrc [new_CkImap]

#  Connect to our source IMAP server.
set success [CkImap_Connect $imapSrc "imap.example.com"]
if {$success == 0} then {
    puts [CkImap_lastErrorText $imapSrc]
    delete_CkImap $imapSrc
    exit
}

#  Login to the source IMAP server
set success [CkImap_Login $imapSrc "admin@chilkatsoft.com" "myPassword"]
if {$success == 0} then {
    puts [CkImap_lastErrorText $imapSrc]
    delete_CkImap $imapSrc
    exit
}

set imapDest [new_CkImap]

#  Connect to our destination IMAP server.
set success [CkImap_Connect $imapDest "mail.example-code.com"]
if {$success == 0} then {
    puts [CkImap_lastErrorText $imapDest]
    delete_CkImap $imapSrc
    delete_CkImap $imapDest
    exit
}

#  Login to the destination IMAP server
set success [CkImap_Login $imapDest "myLogin" "myPassword"]
if {$success == 0} then {
    puts [CkImap_lastErrorText $imapDest]
    delete_CkImap $imapSrc
    delete_CkImap $imapDest
    exit
}

#  Select an IMAP mailbox on the source IMAP server
set success [CkImap_SelectMailbox $imapSrc "Inbox"]
if {$success == 0} then {
    puts [CkImap_lastErrorText $imapSrc]
    delete_CkImap $imapSrc
    delete_CkImap $imapDest
    exit
}

#  After selecting a mailbox, the NumMessages property will
#  be updated to reflect the total number of emails in the mailbox:
puts [CkImap_get_NumMessages $imapSrc]

#  The emails in the mailbox will always have sequence numbers
#  ranging from 1 to NumMessages.

#  This example will copy the first 10 messages using sequence numbers
set sbMime [new_CkStringBuilder]

for {set seqNum 1} {$seqNum <= 10} {incr seqNum} {
    CkStringBuilder_Clear $sbMime
    set success [CkImap_FetchSingleAsMimeSb $imapSrc $seqNum 0 $sbMime]
    if {$success == 0} then {
        puts [CkImap_lastErrorText $imapSrc]
        delete_CkImap $imapSrc
        delete_CkImap $imapDest
        delete_CkStringBuilder $sbMime
        exit
    }

    set success [CkImap_AppendMimeWithFlagsSb $imapDest "Inbox" $sbMime 0 0 0 0]
    if {$success == 0} then {
        puts [CkImap_lastErrorText $imapDest]
        delete_CkImap $imapSrc
        delete_CkImap $imapDest
        delete_CkStringBuilder $sbMime
        exit
    }

}

#  Disconnect from the IMAP servers.
set success [CkImap_Disconnect $imapSrc]
set success [CkImap_Disconnect $imapDest]

delete_CkImap $imapSrc
delete_CkImap $imapDest
delete_CkStringBuilder $sbMime