Deleting IMAP-mails using Python

I'm using a web-based client to access my mailbox. It's simple and contains a basic set of tools for reading, writing and deleting mails. But one thing that I can't do with the client is to search for a group of messages and then delete them.

I might, of course, try to find another client to use...but because I'm a programmer I wanted to solve this the hard-but-fun way.

After taking a IMAP-crash course I wrote the following Python hack..

import imaplib

host = "insert.host.here"
usr = "my_user"
pwd = "my_password"

search_for_subject = '"enter part of subject here"'

im = imaplib.IMAP4(host)
im.login(usr,pwd)
im.select()

result = im.search(None, "SUBJECT",search_for_subject)[1][0].split()

# set testrun to True for just displaying the mails to delete.
# set testrun to False to delete the mails.
testrun = True

for n in result:
   if testrun:
      f = im.fetch(n,'(BODY[HEADER.FIELDS (SUBJECT)])')
      print f[1][0][1].splitlines()[0]
   else:
      im.store(n, '+FLAGS', '\Deleted')

if not testrun:
   im.expunge()

Related links


Comment this note:

Your name:
Your email (hidden):
Message:
Enter the validation code :
Private! (visible for webmaster only)

No messages yet.