Slight detour from the pythonic nature of this blog. I'm almost out of disk space at work, and most of the email is unnecessary. So, I wrote the java class below to delete all mail older the a month. You'll need javamail on your classpath and a compiled class of this:
package us.d8u;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
public class CleanupGmail {
private static Session session = null;
public static void cleanup(String folderName) throws NoSuchProviderException, MessagingException {
Store store = session.getStore("imaps");
if (!store.isConnected()) {
store.connect(System.getProperty("mail.imaps.host"), System.getProperty("mail.imaps.user"), System.getProperty("mail.imaps.password"));
}
Folder inbox = store.getFolder(folderName);
inbox.open(Folder.READ_WRITE);
Message messages[] = inbox.getMessages();
for (Message message : messages) {
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, -1);
Date receivedDate = message.getReceivedDate();
if (receivedDate.before(c.getTime())) {
Flags deleted = new Flags(Flags.Flag.DELETED);
inbox.setFlags(messages, deleted, true);
}
}
inbox.close(true);
}
public static void main(String[] args) {
final Properties props = System.getProperties();
props.setProperty("mail.imaps.host", "imap.gmail.com");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.connectiontimeout", "5000");
props.setProperty("mail.imaps.timeout", "5000");
if (props.getProperty("mail.imaps.user") == null) {
props.setProperty("mail.imaps.user", args[0]);
}
if (props.getProperty("mail.imaps.password") == null) {
props.setProperty("mail.imaps.password", args[1]);
}g
try {
session = Session.getDefaultInstance(props, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(props.getProperty("mail.imaps.user"), props.getProperty("mail.imaps.password"));
}
});
cleanup("[Gmail]/All Mail");
} catch (NoSuchProviderException e) {.
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}
}
You run it using java -jar ~/bin/CleanupGmail.jar -Dmail.imaps.user=<your gmail username> -Dmail.imaps.password=<your gmail password>. Personally, I've just stuck it in a monthly cron job.
No comments:
Post a Comment