gmail.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- coding: utf-8 -*-
  2. import logging
  3. from gmail import Gmail as Gmail_lib
  4. from email.header import decode_header
  5. from core.NeuronModule import NeuronModule, MissingParameterException
  6. logging.basicConfig()
  7. logger = logging.getLogger("kalliope")
  8. class Gmail(NeuronModule):
  9. def __init__(self, **kwargs):
  10. super(Gmail, self).__init__(**kwargs)
  11. # check if parameters have been provided
  12. username = kwargs.get('username', None)
  13. password = kwargs.get('password', None)
  14. if username is None:
  15. raise MissingParameterException("Username parameter required")
  16. if password is None:
  17. raise MissingParameterException("Password parameter required")
  18. # prepare a returned dict
  19. returned_dict = dict()
  20. g = Gmail_lib()
  21. g.login(username, password)
  22. # check if login succeed
  23. logging.debug("Gmail loggin ok: %s" % g.logged_in) # Should be True, AuthenticationError if login fails
  24. # get unread mail
  25. unread = g.inbox().mail(unread=True)
  26. returned_dict["unread"] = len(unread)
  27. if len(unread) > 0:
  28. # add a list of subject
  29. subject_list = list()
  30. for email in unread:
  31. email.fetch()
  32. encoded_subject = email.subject
  33. subject = self._parse_subject(encoded_subject)
  34. subject_list.append(subject)
  35. returned_dict["subjects"] = subject_list
  36. logger.debug("gmail neuron returned dict: %s" % str(returned_dict))
  37. # logout of gmail
  38. g.logout()
  39. self.say(returned_dict)
  40. def _parse_subject(self, encoded_subject):
  41. dh = decode_header(encoded_subject)
  42. return ''.join([self.try_parse(t[0], t[1]) for t in dh])
  43. @staticmethod
  44. def try_parse(header, encoding):
  45. if encoding is None:
  46. encoding = 'ASCII'
  47. try:
  48. return unicode(header, encoding)
  49. except UnicodeDecodeError:
  50. try:
  51. return unicode(header, 'ISO-8859-1')
  52. except UnicodeDecodeError:
  53. return unicode(header, 'UTF-8')