Searching IMAP with Python

23 Aug 2011

M = imaplib.IMAP4_SSL("imap.mail.com")
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, '(SUBJECT "test")')
for num in data[0].split():
  typ, data = M.fetch(num, '(RFC822)')
  print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()

This will search all emails for one with the subject line “test”.
Change the ‘(SUBJECT “test”)’ to whatever you want to search for/in.
There is a good comprehensible list of the commands in the PHP documentaion.
The things in the “Criteria” list can all be used insted of the ’(SUBJECT “test”) string.

blog comments powered by Disqus