Docs updated

This commit is contained in:
Martin Rusev
2013-07-23 15:13:32 +03:00
parent 7a77c53722
commit adf34d3ade
2 changed files with 71 additions and 10 deletions

View File

@@ -24,5 +24,33 @@ Usage
# Every message is converted to a dictionary with the following keys:
{
'MesssageID': '22c74902-a0c1-4511-804f2-341342852c90',
'From': {
'Name': 'John Doe',
'Email': 'jonhdoe@email.com'
},
'To': {
'Name': 'Martin Rusev',
'Email': 'martin@amon.cx'
},
'Date': 'Mon, 22 Jul 2013 23:21:39 +0000 (UTC)',
'TextBody': ['ASCII'],
'Subject': 'This is a message'
'Headers': [{
'Name': 'Received-SPF',
'Value': 'pass (google.com: domain of bounces+......;'
}, {
'Name': 'MIME-Version',
'Value': '1.0'
}],
}

View File

@@ -12,23 +12,57 @@ class MailBox(object):
def parse_email(self, raw_email): def parse_email(self, raw_email):
email_message = email.message_from_string(raw_email) email_message = email.message_from_string(raw_email)
headers = dict(email_message.items())
maintype = email_message.get_content_maintype() maintype = email_message.get_content_maintype()
message = [] text_body = []
if maintype == 'multipart': if maintype == 'multipart':
for part in email_message.get_payload(): for part in email_message.walk():
if part.get_content_maintype() == 'text': if part.get_content_type() == "text/plain":
message.append(part.get_payload(decode=True)) text_body.append(part.get_payload(decode=True))
elif maintype == 'text': elif maintype == 'text':
message.append(email_message.get_payload(decode=True)) text_body.append(email_message.get_payload(decode=True))
email_dict = dict(email_message.items())
from_dict = {}
from_ = email.utils.parseaddr(email_dict['From'])
if len(from_) == 2:
from_dict = {'Name': from_[0], 'Email': from_[1]}
to_dict = {}
to_ = email.utils.parseaddr(email_dict['To'])
if len(to_) == 2:
to_dict = {'Name': to_[0], 'Email': to_[1]}
subject = email_dict.get('Subject', None)
date = email_dict.get('Date', None)
message_id = email_dict.get('Message-ID', None)
# Get the headers
headers = []
headers_keys = ['Received-SPF',
'MIME-Version',
'X-Spam-Status',
'X-Spam-Score']
for key in headers_keys:
header_value = email_dict.get(key)
if header_value:
headers.append({'Name': key,
'Value': header_value})
return { return {
'message': message, 'MesssageID': message_id,
'headers': headers, 'From': from_dict,
'maintype': maintype 'To': to_dict,
'Subject': subject,
'Date': date,
'TextBody': text_body,
'Headers': headers
} }
def fetch_by_uid(self, uid): def fetch_by_uid(self, uid):
@@ -58,4 +92,3 @@ class MailBox(object):
message, data = self.connection.uid('search', None, "UNSEEN") message, data = self.connection.uid('search', None, "UNSEEN")
return self.fetch_list(data) return self.fetch_list(data)