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

Get IMAP UID from Email Header

See more IMAP Examples

Demonstrates how to get the IMAP UID from an email header. After fetching an email or header using IMAP, the UID is contained in the ckx-imap-uid header field.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.EmailBundle;
import com.chilkatsoft.chilkat2.Imap;
import com.chilkatsoft.chilkat2.MessageSet;

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 imap = new Imap();

        // Connect to an IMAP server.
        // Use TLS
        imap.setSsl(true);
        imap.setPort(993);
        try {
            imap.connect("imap.example.com");

            // Login
            imap.login("login", "password");

            // Select an IMAP mailbox
            imap.selectMailbox("Inbox");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        boolean fetchUids = true;
        // Get the message UIDs of all the emails in the mailbox

        MessageSet messageSet = new MessageSet();
        try {
            imap.queryMbx("ALL", fetchUids, messageSet);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        EmailBundle bundle = new EmailBundle();
        boolean headersOnly = true;
        try {
            imap.fetchMsgSet(headersOnly, messageSet, bundle);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // The UID of each fetched email header is available
        // in the ckx-imap-uid header field.
        Email email = new Email();
        MessageSet msgSet1 = new MessageSet();
        int i = 0;
        int szBundle = bundle.getMessageCount();
        while (i < szBundle) {
            bundle.emailAt(i, email);

            // Build a message set containing one UID
            String uidStr = email.getHeaderField("ckx-imap-uid");
            msgSet1.fromCompactString(uidStr);

            // Move this message to some other folder.
            try {
                imap.moveMessages(msgSet1, "someOtherFolder");
            } catch (ChilkatException e) {
                System.out.println(e.getLastErrorText());
                // Exit the loop...
                i = szBundle;
            }

            i = i + 1;
        }

        // Disconnect from the IMAP server.
        imap.disconnect();
    }
}