Permalink
Browse files

Added module for basic envelope parsing.

  • Loading branch information...
1 parent 103964b commit d8b927692919c643965b87a1f3effd5cc72c482d @rca committed Mar 5, 2013
Showing with 55 additions and 0 deletions.
  1. +33 −0 imapbot/envelope.py
  2. +22 −0 tests/test_envelope.py
View
@@ -0,0 +1,33 @@
+"""
+Module to retrieve envelope fields by name, not just index
+"""
+
+
+class Envelope(tuple):
+ fields = (
+ 'date', # Returns a string that represents the date.
+ 'subject', # Returns a string that represents the subject.
+ 'from', # Returns a list of addresses that represents the from.
+ 'sender', # Returns a list of addresses that represents the sender.
+ 'reply_to', # Returns a list of addresses that represents the reply-to.
+ 'to', # Returns a list of addresses that represents the to.
+ 'cc', # Returns a list of addresses that represents the cc.
+ 'bcc', # Returns a list of addresses that represents the bcc.
+ 'in_reply_to', # Returns a string that represents the in-reply-to.
+ 'message_id', # Returns a string that represents the message-id.
+ )
+
+ def __getitem__(self, field):
+ try:
+ index = self.fields.index(field)
+ return super(Envelope, self).__getitem__(index)
+ except ValueError:
+ if type(field) != int:
+ raise ValueError('"{}" is not an envelope field'.format(field))
+
+ return super(Envelope, self).__getitem__(field)
+
+ def get_email(self, field):
+ value = self[field][0]
+
+ return '@'.join((value[2], value[3]))
View
@@ -0,0 +1,22 @@
+from unittest import TestCase
+
+from imapbot.envelope import Envelope
+
+from helpers import SAMPLE_ENVELOPE
+
+
+class EnvelopeTestCase(TestCase):
+ def setUp(self):
+ self.envelope = Envelope(SAMPLE_ENVELOPE)
+
+ def test_value_error(self):
+ self.assertRaises(ValueError, lambda: self.envelope['nothere'])
+
+ def test_get_by_name(self):
+ self.assertEqual('Mon, 4 Mar 2013 17:51:24 -0800', self.envelope['date'])
+
+ def test_get_by_index(self):
+ self.assertEqual('Mon, 4 Mar 2013 17:51:24 -0800', self.envelope[0])
+
+ def test_get_email(self):
+ self.assertEqual('roberto.c.aguilar@gmail.com', self.envelope.get_email('from'))

0 comments on commit d8b9276

Please sign in to comment.