Skip to content

Commit

Permalink
Added module for basic message parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
rca committed Mar 5, 2013
1 parent d8b9276 commit 9794723
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 0 deletions.
62 changes: 62 additions & 0 deletions imapbot/message.py
@@ -0,0 +1,62 @@
from imapbot.envelope import Envelope


class Message(object):
def __init__(self, id, envelope, text, flags):
self.id = id
self.flags = flags
self.envelope = Envelope(envelope)
self.text = text

self._parsed = None

@property
def parsed(self):
if self._parsed:
return self._parsed

split = self.text.splitlines()

parsed = {}

marker = split[-1]
if marker.startswith('--') and marker.endswith('--'):
body = []
content_type = None

# this is a multipart message body
idx = 0
while idx < len(split):
line = split[idx]

if line and marker.startswith(line):
if content_type is not None:
parsed[content_type] = '\r\n'.join(body)

content_type = None
body = []

idx += 1
continue

elif line.startswith('Content-Type'):
content_type = line.split(';', 1)[0].split(' ', 1)[-1]
idx += 2
continue

body.append(line)
idx += 1
else:
parsed['text/plain'] = self.text

self._parsed = parsed

return self._parsed

@property
def html(self):
return self.parsed['text/html']

@property
def plain(self):
return self.parsed['text/plain']
11 changes: 11 additions & 0 deletions tests/files/message.txt
@@ -0,0 +1,11 @@
--14dae934074550562a04d71f436a
Content-Type: text/plain; charset=ISO-8859-1

testing.

--14dae934074550562a04d71f436a
Content-Type: text/html; charset=ISO-8859-1

<div dir="ltr">testing.</div>

--14dae934074550562a04d71f436a--
29 changes: 29 additions & 0 deletions tests/test_message.py
@@ -0,0 +1,29 @@
import os

from unittest import TestCase

from imapbot.message import Message

from tests.helpers import SAMPLE_ENVELOPE

MODULE_DIR = os.path.dirname(__file__)


class MessageTestCase(TestCase):
def __init__(self, methodName='runTest'):
super(MessageTestCase, self).__init__(methodName=methodName)

with open(os.path.join(MODULE_DIR, 'files', 'message.txt')) as fh:
self.message_text = fh.read()

def setUp(self):
self.message = Message(1, SAMPLE_ENVELOPE, self.message_text, None)

def test_parse_body(self):
self.assertEqual(2, len(self.message.parsed))

def test_plain(self):
self.assertEqual('testing.\r\n', self.message.plain)

def test_html(self):
self.assertEqual('<div dir="ltr">testing.</div>\r\n', self.message.html)

0 comments on commit 9794723

Please sign in to comment.