Java Requires Chilkat v11.0.0+
Chilkat2 Java
Delete Email Individually (One at a time) from an IMAP Mailbox
Downloads email from an IMAP mailbox and deletes emails individually (one by one).Chilkat Java Downloads
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();
// 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;
}
// We can choose to fetch UIDs or sequence numbers.
boolean fetchUids = true;
// Get the message IDs of all the emails in the mailbox
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);
// To mark a complete set of emails for deletion, call SetFlags:
imap.setFlags(messageSet, "Deleted", 1);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Messages can also be marked for deletion individually:
// Loop over the bundle and mark each message for deletion.
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());
// To delete this email, set the "Deleted" flag to 1.
// The email is not actually deleted until Expunge or
// ExpungeAndClose is called.
try {
imap.setMailFlag(email, "Deleted", 1);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("--");
i = i + 1;
}
try {
imap.expungeAndClose();
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Disconnect from the IMAP server.
imap.disconnect();
}
}