Question

I realize there are a number of libraries to access IMAP, from Java, Python, etc. But what I want to do is very specific, and is counter to most imap examples.

The easy parts:

  • Given an IMAP server, login, and specific folder name
  • Nuke all messages in that folder (Or Nuke the folder, if that's easier or more efficient?)

The atypical parts:

  • Do an expunge after every N deletes
  • Include some retry and batch size logic so that busy servers - even deleting and expunging 100 messages per session would be a help.
  • DON'T download all the headers!

That last point is a problem. Every email client I've tried chokes on downloading the 20,000 email headers - which I don't need to see.

With POP3 scripting I've just given sequential IDs, 1, 2, 3 ...

But every IMAP example I've seen appears to use some field that it got from the headers. So maybe deleting IMAP messages requires an ID that you can't guess at? (and can only get by doing a query?)

If I did need to get headers, can this at least be made as compact as possible? Or let me do just 100 at a time?

Alternatively, I've tried to delete an entire folder via email client UI's, but this doesn't seem to work. I think it's trying to move all the headers to the trash first, and fails at that, so never gets to the expunge part. So I'm not sure that deleting a folder is actually more efficient than deleting its contents.

Any thoughts appreciated. I usually work in Java or Python, but I'm flexible. I think this is a protocol issue, not a library issue.

Was it helpful?

Solution

Assuming you're not using an atypical server (like gmail which is quite atypical) you can do these commands, after LOGIN, and SELECT [folder]:

A001 STORE 1:N +FLAGS (\Deleted)
A002 EXPUNGE
A003 STORE 1:N +FLAGS (\Deleted)
A004 EXPUNGE

And so on, where you replace N with your batch size. This will not use the trash folder (unless your IMAP server has special logic, like Gmail: for gmail, tweak your IMAP access settings).

You should be able to do this:

A001 STORE 1:* +FLAGS (\Deleted)
A002 EXPUNGE

That may take a while though.

In fact, you can use a tool like socat to login and speak the protocol yourself:

socat READLINE: OPENSSL:[server]:993,noverify,crlf
a LOGIN [user] "[password]"
b SELECT [folder]

And then the store and expunge commands from above.

OTHER TIPS

The IMAP specification provides a DELETE command that can destroy an entire mailbox.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top