Email parser updated

This commit is contained in:
Martin Rusev
2013-07-23 12:01:59 +03:00
parent 760153d12e
commit bc9f98e2c8
4 changed files with 44 additions and 17 deletions

5
.gitignore vendored
View File

@@ -29,8 +29,5 @@ nosetests.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
example.*
example.py

View File

@@ -1,13 +0,0 @@
import sys
sys.path.insert(0, '/home/martin/mailbox')
from mailbox import MailBox
mailbox = MailBox('imap.gmail.com',
username='username',
password='password')
unread = mailbox.get_unread()
for message in unread:
print message.json()

View File

@@ -1,3 +1,4 @@
import email
from mailbox.imap import ImapTransport
class MailBox(object):
@@ -8,5 +9,39 @@ class MailBox(object):
self.connection = server.connect(username, password)
def parse_email(self, raw_email):
email_message = email.message_from_string(raw_email)
headers = dict(email_message.items())
maintype = email_message.get_content_maintype()
message = []
if maintype == 'multipart':
for part in email_message.get_payload():
if part.get_content_maintype() == 'text':
message.append(part.get_payload(decode=True))
elif maintype == 'text':
message.append(email_message.get_payload(decode=True))
return {
'message': message,
'headers': headers,
'maintype': maintype
}
def get_unread(self):
result, data = self.connection.uid('search', None, "ALL") # search and return uids instead
latest_email_uid = data[0].split()[-1]
result, data = self.connection.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = data[0][1]
print self.parse_email(raw_email)
return {}

View File

@@ -17,8 +17,16 @@ class ImapTransport(object):
if not self.port:
self.port = 143
def list_folders(self):
return self.server.list()
def connect(self, username, password):
self.server = self.transport(self.hostname, self.port)
typ, msg = self.server.login(username, password)
self.server.select()
return self.server