import javax.mail.*; import javax.mail.internet.*; // Configuration below... type = "imap" // (or pop3) host = "domain.com" user = "username" pass = "password" deleteOn = "Undelivered Mail Returned to Sender" // This is the subject line to search for. Any messages matching will be deleted. testRun = true; // if this is true, it will only make 5 passes and then exit. passes = 5; // Number of passes to make before closing the connection and committing changes // End configuration... moreAvailable = true; progStart = System.currentTimeMillis(); while(moreAvailable) { // -- Get hold of the default session -- Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props, null); // -- Get hold of a POP3 message store, and connect to it -- Store store = session.getStore(type); store.connect(host, user, pass); // -- Try to get hold of the default folder -- Folder folder = store.getDefaultFolder(); if(folder == null) throw new Exception("No default folder"); // -- ...and its INBOX -- folder = folder.getFolder("INBOX"); if(folder == null) throw new Exception("No " + type + " INBOX"); // -- Open the folder for read only -- folder.open(Folder.READ_WRITE); // -- Get the message wrappers and process them -- int total = folder.getMessageCount(); if(total < 700) { moreAvailable = false; } println "Total messages: " + total; long start = System.currentTimeMillis(); long lastTime = System.currentTimeMillis(); int testCount = 0; int page = 100; for(i in 0..(total/page)) { println(" Elapsed Time: " + (System.currentTimeMillis() - start) + " MS"); println("Deleting messages[" + (total - (page * (i + 1))) + ", " + (total - (page * i)) + "]"); messages = folder.getMessages(total - (page * (i + 1)), total - (page * i)); for(m in messages) { if(m.getSubject().equals(deleteOn)) { print "." m.setFlag(Flags.Flag.DELETED, true); } } println "" testCount++; if(testRun && testCount > 5) { break; } print "Deletion took: " + (System.currentTimeMillis() - lastTime) + " MS"; lastTime = System.currentTimeMillis(); } println "Committing changes..."; folder.expunge(); folder.close(true); store.close(); println("Pass took: " + (System.currentTimeMillis() - start) + " MS"); } println("Total time to cleanup: " + (System.currentTimeMillis() - progStart) + " MS");