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

Delete IMAP Email

To delete an email, the "Deleted" flag must be set to 1 for each message to be deleted. You must also call Expunge or ExpungeAndClose to remove the emails marked as deleted.

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

        // This example deletes email matching a criteria from Inbox.
        Imap imap = new Imap();

        // Turn on session logging:
        imap.setKeepSessionLog(true);

        // Connect to an 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;
        // Get the message IDs for all emails having "FTP2" in the subject.
        MessageSet messageSet = new MessageSet();
        try {
            imap.queryMbx("SUBJECT FTP2", fetchUids, messageSet);

            // Set the Deleted flag for each message:
            imap.setFlags(messageSet, "Deleted", 1);

            // Expunge and close the mailbox.
            imap.expungeAndClose();
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Display the session log.
        System.out.println(imap.getSessionLog());

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