#!/usr/bin/env python import imaplib import smtplib import time from email.MIMEText import MIMEText import re PATTERN = re.compile(r'\((?P.*?)\) "(?P.*)" (?P.*)') class Account(object): """Imap account.""" def __init__(self, email, password): """Login instantly""" self.imap = imaplib.IMAP4() self.imap.login(email, password) self.name = email.split('@')[0] def __del__(self): self.imap.logout() def delete_box(self, name): """Remove mailbox except INBOX""" if name != 'INBOX': self.imap.delete(name) def clean_box(self, name='INBOX'): """Delete all messagess from the mailbox""" self.imap.select(name) try: typ, [ids] = self.imap.search(None, 'ALL') ids = ','.join(ids.split()) if ids: typ, response = self.imap.store(ids, '+FLAGS', r'(\Deleted)') typ, response = self.imap.expunge() finally: self.imap.close() if name != 'INBOX': self.imap.delete(name) def get_box_list(self): box_list = [] typ, data = self.imap.list() for line in data: flags, delimiter, mailbox_name = PATTERN.match(line).groups() box_list.append(mailbox_name.strip('"')) return box_list def get_from_box(self, name='INBOX'): """Get all messages from the mailbox""" self.imap.select(name, readonly=True) msg = {} out = [] try: resp, items = self.imap.search(None, 'ALL') print items for item in items[0].split(): typ, msg_data = self.imap.fetch(item, '(BODY.PEEK[HEADER])') msg['HEADER'] = msg['TEXT'] = '' msg['FLAGS'] = [] for response_part in msg_data: if isinstance(response_part, tuple): msg['HEADER'] += response_part[1] typ, msg_data = self.imap.fetch(item, '(BODY.PEEK[TEXT])') for response_part in msg_data: if isinstance(response_part, tuple): msg['TEXT'] += response_part[1] typ, msg_data = self.imap.fetch(item, '(FLAGS)') for response_part in msg_data: msg['FLAGS'].append(( response_part, imaplib.ParseFlags(response_part) )) out.append(msg) finally: self.imap.close() return out if __name__ == '__main__': me = Account('me@virtualworld.com', '123') clone = Account('clone@virtualworld.com', '123') foe = Account('foe@virtualworld.com', '123') for acc in [me, foe, clone]: for box in acc.get_box_list(): pass #acc.clean_box(box) friend_msg = MIMEText("I'm your friend") friend_msg['From'] = 'friend@virtualworld.com' friend_msg['To'] = 'me@virtualworld.com' friend_msg['Subject'] = 'The message from your friend.' foe_msg = MIMEText("I'm your foe") foe_msg['From'] = 'foe@virtualworld.com' foe_msg['To'] = 'me@virtualworld.com' foe_msg['Subject'] = 'The message from your foe.' spammer_msg = MIMEText("It's spam") spammer_msg['From'] = 'foe@virtualworld.com' spammer_msg['To'] = 'me@virtualworld.com' spammer_msg['Subject'] = 'SPAM SPAM SPAM' server = smtplib.SMTP('localhost') for msg in [friend_msg, foe_msg, spammer_msg]: server.sendmail(msg['From'], msg['To'], msg.as_string()) time.sleep(1) for acc in [me, foe, clone]: for box in acc.get_box_list(): out = acc.get_from_box(box) for msg in out: print '*' * 79 print '* Account', acc.name print '* Mailbox', box print '-' * 79 print '* Headers' print msg['HEADER'] print '-' * 79 print '* Body' print msg['TEXT'] print '-' * 79 print '* Flags' print msg['FLAGS']