import mailbox, imaplib, re, email from mailreactor.app import markup, MailArchive class ImapCheck: def __init__(self): self.IMAP_SERVER='IP.IP.IP.IP' self.IMAP_PORT=993 self.M = None self.response = None self.mailboxes = [] def login(self, username, password): self.M = imaplib.IMAP4_SSL(self.IMAP_SERVER, self.IMAP_PORT) rc, self.response = self.M.login(username, password) return rc def logout(self): self.M.logout() def content_email(self, num): """ Email header """ self.head = [] typ, msg_data = self.M.fetch(num, '(BODY.PEEK[HEADER])') for response_part in msg_data: if isinstance(response_part, tuple): self.header_view = response_part[1] msg = email.message_from_string(response_part[1]) for header in [ 'subject', 'to', 'from', 'date', 'Message-ID']: self.head.append(msg[header]) """ Email content """ self.messagePlainText = '' self.messageHTML = '' self.messageAttachments = [] typ, msg_data = self.M.fetch(num, '(RFC822)') for response_part in msg_data: if isinstance(response_part, tuple): self.body = response_part[1] msg = email.message_from_string(response_part[1]) for part in msg.walk(): #http://docs.python.org/library/email.message.html if str(part.get_content_type()) == 'text/plain': self.messagePlainText = self.messagePlainText + str(part.get_payload()) if str(part.get_content_type()) == 'text/html': self.messageHTML = self.messageHTML + str(part.get_payload()) if part.get_filename(): self.messageAttachments.append((part.get_filename(), part.get_payload(decode=true))) """ Email flag """ typ, msg_data = self.M.fetch(num, '(FLAGS)') for response_part in msg_data: self.flag = imaplib.ParseFlags(response_part) context = { 'header_view': self.header_view, 'head': self.head, 'body': self.body, 'messagePlainText': self.messagePlainText, 'messageHTML': self.messageHTML, 'messageAttachments': self.messageAttachments, 'flag': self.flag, } return context def get_mails(self, folder='INBOX'): status, count = self.M.select(folder, readonly=1) status, response = self.M.search('UTF-8', 'Unseen') for num in response[0].split(): entry = MailArchive() data = self.content_email(num) import uuid entry['_id'] = unicode(uuid.uuid4()) entry['header'] = unicode(data['header_view']) entry['head_subject'] = unicode(data['head'][0]) entry['head_to'] = unicode(data['head'][1]) entry['head_from'] = unicode(data['head'][2]) entry['head_date'] = unicode(data['head'][3]) entry['message_id'] = unicode(data['head'][4]) entry['body'] = markup(unicode(data['body']), escape=True, small_headings=False) entry['body_text'] = unicode(data['messagePlainText']) entry['body_html'] = unicode(data['messageHTML']) entry['flag'] = unicode(data['flag'][0]) entry.save() doc = data['messageAttachments'] for k, v in doc: entry.put_attachment(v, unicode(k)) typ, response = self.M.store(num, '+FLAGS', '\Seen') return def read_mailbox(): entry = MailArchive() c = ImapCheck() c.login('name@email.com', 'passwd') email = c.get_mails() c.logout() return email