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

IMAP STARTTLS (Explicit TLS/SSL)

The StartTls property is set to force the Connect method to automatically convert an connection to TLS/SSL via the STARTTLS IMAP command.

This is also known as "explicit TLS/SSL" as opposed to "implicit TLS/SSL". With implicit TLS/SSL, the IMAP client connects on the well-known IMAP TLS/SSL port 993 and the secure channel is immediately established. With explicit TLS/SSL, the IMAP client connects on the typical non-secure port (143 usually) and the converts the connection via the STARTTLS command.

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 assumes the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        Imap imap = new Imap();

        // Indicate that STARTTLS should be used to convert
        // to a secure TLS/SSL connection:
        imap.setStartTls(true);
        imap.setPort(143);

        // Connect to an IMAP server and convert the connection
        // to TLS/SSL via STARTTLS.
        try {
            imap.connect("imap.example.com");

            // The remainder of this example is the same as for
            // non-TLS/SSL...

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

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

        // Get the message IDs of all the emails in the mailbox
        boolean fetchUids = true;
        MessageSet messageSet = new MessageSet();
        try {
            imap.queryMbx("ALL", fetchUids, messageSet);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

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

        // Loop over the bundle and display the FROM and SUBJECT of each.
        Email email = new Email();
        int i = 0;
        int numEmails = bundle.getMessageCount();
        while (i < numEmails) {
            bundle.emailAt(i, email);

            System.out.println(email.getFrom());
            System.out.println(email.getSubject());
            System.out.println("--");
            i = i + 1;
        }

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