Sample code for 30+ languages & platforms
Java 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 Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Imap;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        Imap imapSrc = new Imap();

        // Connect to our source IMAP server.
        try {
            imapSrc.connect("imap.example.com");

            // Login to the source IMAP server
            imapSrc.login("admin@chilkatsoft.com", "myPassword");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        Imap imapDest = new Imap();

        // Connect to our destination IMAP server.
        try {
            imapDest.connect("mail.example-code.com");

            // Login to the destination IMAP server
            imapDest.login("myLogin", "myPassword");

            // Select an IMAP mailbox on the source IMAP server
            imapSrc.selectMailbox("Inbox");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // After selecting a mailbox, the NumMessages property will
        // be updated to reflect the total number of emails in the mailbox:
        System.out.println(imapSrc.getNumMessages());

        // 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
        StringBuilder sbMime = new StringBuilder();
        for (int seqNum = 1; seqNum <= 10; seqNum++) {
            sbMime.clear();
            try {
                imapSrc.fetchSingleAsMimeSb(seqNum, false, sbMime);

                imapDest.appendMimeWithFlagsSb("Inbox", sbMime, false, false, false, false);
            } catch (ChilkatException e) {
                System.out.println(e.getLastErrorText());
                return;
            }
        }

        // Disconnect from the IMAP servers.
        imapSrc.disconnect();
        imapDest.disconnect();
    }
}