Skip to content

Instantly share code, notes, and snippets.

@5263
Created June 28, 2012 19:10
Show Gist options
  • Save 5263/3013270 to your computer and use it in GitHub Desktop.
Save 5263/3013270 to your computer and use it in GitHub Desktop.
List new e-mails from IMAP mailbox ordered by spamscore
#!/usr/bin/env python
import imaplib,getpass
import email
import email.header
import email.utils
import re
def decodestr(str1):
str2,enc=email.header.decode_header(str1)[0]
if enc:
return str2.decode(enc)
else:
return str2
hetz=imaplib.IMAP4('mail.hetzner.de')
hetz.login('user@domain.de', getpass.getpass())
hetz.select('INBOX',1)
typ, data = hetz.search(None, '(OR (RECENT) (UNSEEN))')
msgs=[]
if typ == 'OK':
for num in data[0].split():
typ, data = hetz.fetch(num, '(BODY[HEADER])')
obj=email.message_from_string(data[0][1])
spamscore=float(re.search('([-+]?[0-9]*\.?[0-9]+)',\
obj.get('X-Spam-Score','0')).group())
msgs.append((obj,num,spamscore))
msgs.sort(key=lambda tpl: tpl[2])
for obj,num,spamscore in msgs[::-1]:
date=email.utils.parsedate_tz(obj.get('Date'))
if date:
datestr = '%04d-%02d-%02d %02d:%02d:%02d' % date[0:6]
else:
datestr ='?'
print '%4s %5.1f' % (num,spamscore), datestr, obj.get('From')[0:48]
if spamscore < 10:
print decodestr(obj.get('Subject'))[0:78]
hetz.close()
hetz.logout()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment