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

Sorting Email

Demonstrates how to sort an email bundle.

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 the IMAP server.
        // Use TLS
        imap.setSsl(true);
        imap.setPort(993);
        try {
            imap.connect("imap.example.com");

            // Login
            imap.login("myLogin", "myPassword");

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

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

        // Fetch the email headers into a bundle object:
        EmailBundle bundle = new EmailBundle();
        boolean headersOnly = true;
        try {
            imap.fetchMsgSet(headersOnly, messageSet, bundle);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Sort the email bundle by date, recipient, sender, or subject:
        boolean ascending = true;
        bundle.sortByDate(ascending);

        // To sort by recipient, sender, or subject, call
        // SortBySender, SortByRecipient, or SortBySubject.

        // Display the Subject and From of each email.
        Email email = new Email();
        int i = 0;
        while (i < bundle.getMessageCount()) {
            bundle.emailAt(i, email);

            System.out.println(email.getHeaderField("Date"));
            System.out.println(email.getSubject());
            System.out.println(email.getFrom());
            System.out.println("--");

            i = i + 1;
        }

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