Java Requires Chilkat v11.0.0+
Chilkat2 Java
IMAP Delete Old Email (before a specified date)
See more IMAP Examples
Demonstrates how to delete email older than a particular date.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
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();
// Connect to an IMAP server.
// Use TLS
imap.setSsl(true);
imap.setPort(993);
// Use your IMAP server domain. This example
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;
}
// Get message ID's for emails older than 1/1/2025
boolean fetchUids = true;
MessageSet messageSet = new MessageSet();
try {
imap.queryMbx("SENTBEFORE 01-Jan-2025", fetchUids, messageSet);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// If desired, we can examine the Subject of each email to be deleted..
Email email = new Email();
int i = 0;
int count = messageSet.getCount();
boolean headerOnly = true;
while (i < count) {
try {
imap.fetchEmail(headerOnly, messageSet.getId(i), true, email);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println(email.getLocalDateStr());
System.out.println(email.getSubject());
i = i + 1;
}
// Set the Deleted flag for each message:
try {
imap.setFlags(messageSet, "Deleted", 1);
// Expunge and close the mailbox.
imap.expungeAndClose();
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Disconnect from the IMAP server.
imap.disconnect();
}
}