Search code examples
javaemailjakarta-mailimap

Connecting to an imap server and processing the contents of the root folder


I am using the following Java sample code to connect to an imap server:

void emailtest(String user, String pass, String server, String port, String folder, String timeout) {
    Properties props = new Properties();
    props.put("mail.store.protocol", "imap");
    props.put("mail.imap.host", server);
    props.put("mail.imap.port", port);
    props.put("mail.imap.ssl.enable", "true");

    Session session = Session.getInstance(props, null);
    try (Store store = session.getStore("imap")) {
        System.out.println("Establishing connection to: " + server);
        store.connect(user, pass);
        System.out.println("Connected!");

        Folder def = store.getDefaultFolder();
        Folder[] tmp = def.list("*");
        Folder[] folders = new Folder[tmp.length + 1];
        System.arraycopy(tmp, 0, folders, 0, tmp.length);
        folders[tmp.length] = def; // this is the root folder

        for(Folder f : folders)
            System.out.println("Foldername: " + f.getName());

// .... further processing of folder contents

As you can see I am also printing the name of the default root folder, which has been an empty String in my tests so far, thus it contains no emails itself.

My question: Does it depend on the email provider, if the root folder will contain any messages or is it safe to assume that the root folder will only contain a list of subfolder, but will never have any email messages itself?


Solution

  • Some IMAP servers will use the INBOX as the root folder, so no, you cannot depend on the root folder not containing any messages.