Browse files

Added module for basic message parsing

  • Loading branch information...
1 parent d8b9276 commit 9794723fcd81e32d3ac928422e2f1fc29f0c31a7 @rca committed Mar 4, 2013
Showing with 102 additions and 0 deletions.
  1. +62 −0 imapbot/message.py
  2. +11 −0 tests/files/message.txt
  3. +29 −0 tests/test_message.py
View
62 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']
View
11 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--
View
29 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.