import imaplib
from email.Parser import HeaderParser

class ImapBoxConnectionError(Exception): pass
class ImapBoxAuthError(Exception): pass

class ImapBox:
	def __init__(self, user, password, 
			host, port = 143, ssl = False,
			use_default_mbox = True,
			mbox_dir = None):
		self.user = user
		self.password = password
		self.port = int(port)
		self.host = host
		self.ssl = ssl
		self.use_default_mbox = use_default_mbox
		self.mbox_dir = mbox_dir

		self.mbox = None
	
	def __connect(self):
		print "connecting to the imap server %s on port %s..." % (self.host, self.port)
		try:
			if not self.ssl:
				self.mbox = imaplib.IMAP4(self.host, self.port)
			else:
				self.mbox = imaplib.IMAP4_SSL(self.host, self.port)
		except Exception:
			raise ImapBoxConnectionError()
		print "... connection done to the server %s on port %s" % (self.host, self.port)

		print "authenticate user ..."
		try:
			self.mbox.login(self.user, self.password)
		except Exception, e:
			raise ImapBoxAuthError()
		print "...auth done"
	
	def get_mails(self):
		
		try:
			self.__connect()
		except ImapBoxConnectionError:
			raise ImapBoxConnectionError()
		except ImapBoxAuthError:
			raise ImapBoxAuthError()

		print "getting mails..."

		mails = []
		try:
			if self.use_default_mbox:
				result, message = self.mbox.select(readonly=1)
			else:
				result, message = self.mbox.select(self.mbox_dir, readonly=1)
			if result != 'OK':
				raise Exception, message

			# retrieve only unseen messages
			typ, data = self.mbox.search(None, 'UNSEEN')
			for num in data[0].split():
				# fetch only needed fields
				f = self.mbox.fetch(num, '(BODY[HEADER.FIELDS (SUBJECT FROM MESSAGE-ID)])')
				hp = HeaderParser()
				m = hp.parsestr(f[1][0][1])
				sub = m['subject']
				fr = m['from']
				sub = sub.replace("<", "&lt;").replace(">", "&gt;")
				sub = sub.replace("&", "&amp;")
				fr = fr.replace("<", "&lt;").replace(">", "&gt;")
				fr.replace("&", "&amp;")
				mails.append([sub, fr, m['Message-ID']])
		except Exception, e:
			print e

		self.mbox.logout()
		print "...done"
		return mails


if __name__ == "__main__":
	#i = ImapBox("", "", "")
	i = ImapBox("", "", "")
	print i.get_mails()
