Sample code for 30+ languages & platforms
Java

Determine the Number of Unseen Email Messages

Demonstrates how to determine how many unseen messages exist in an email account on an IMAP server.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
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("***", "***");

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

        // After selecting the mailbox. the total number of emails
        // is immediately available:
        int totalNum = imap.getNumMessages();
        System.out.println("Num messages = " + totalNum);

        // To determine the number of unseen messages, a call
        // to Search is required, which returns the set of UIDs
        // of all unseen messages.

        // We can choose to fetch UIDs or sequence numbers.
        boolean fetchUids = true;
        MessageSet messageSet = new MessageSet();
        try {
            imap.queryMbx("UNSEEN", fetchUids, messageSet);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        long numUnseen = messageSet.getCount();
        System.out.println(numUnseen);

        System.out.println("UIDs ----");

        // Display the UIDs
        int i = 0;
        while (i < messageSet.getCount()) {
            System.out.println(messageSet.getId(i));
            i = i + 1;
        }

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