Skip to content

Instantly share code, notes, and snippets.

@doppelgunner
Last active November 5, 2017 00:37
Show Gist options
  • Save doppelgunner/c7ab8b982d958245c95f033b0329e17c to your computer and use it in GitHub Desktop.
Save doppelgunner/c7ab8b982d958245c95f033b0329e17c to your computer and use it in GitHub Desktop.
Deleting emails on specific folder - Java + GMAIL
//IMPORTANT: check the image attached in comment or below for gmail settings
//sample of method call: deleteEmails("[Gmail]/Sent Mail", username, password);
public static void deleteEmails(String folder, String user, String password) {
String imapHost = "imap.gmail.com";
String storeType = "imaps";
// get the session object
try {
Properties properties = new Properties();
properties.put("mail.store.protocol", storeType);
properties.put("mail.imaps.host", imapHost);
properties.put("mail.imaps.port","993");
properties.put("mail.imaps.auth","true");
properties.put("mail.imaps.ssl.trust","*");
properties.put("mail.imaps.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore(storeType);
store.connect(imapHost, user, password);
Folder[] f = store.getDefaultFolder().list();
for(Folder fd:f) {
Folder[] fc = fd.list();
for (Folder fc1 : fc) {
System.out.println(fc1);
}
}
Folder emailFolder = store.getFolder(folder);
emailFolder.open(Folder.READ_WRITE);
/*Use this to check all folder
Message[] messages = emailFolder.getMessages();
System.out.println("MESSAGES: " + messages.length);
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
message.setFlag(Flags.Flag.DELETED, true);
}
*/
//closes all messages marked deleted
emailFolder.close(true);
store.close();
Util.notif("Emails deleted successfully...");
} catch (Exception ex) {
Util.notif("Problem deleting emails...");
ex.printStackTrace();
}
}
@doppelgunner
Copy link
Author

capture

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment