You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.9 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2017 Eficent Business and IT Consulting Services S.L. (www.eficent.com)
  3. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  4. import email
  5. import xmlrpclib
  6. import logging
  7. from email.message import Message
  8. from openerp import api, models
  9. from openerp.addons.mail.models.mail_message import decode
  10. _logger = logging.getLogger(__name__)
  11. class MailThread(models.AbstractModel):
  12. _inherit = 'mail.thread'
  13. @api.model
  14. def message_parse_basic_data(self, message):
  15. """Parses a string or email.message.Message representing an RFC-2822
  16. email, and returns a generic dict holding the message details.
  17. :param message: the message to parse
  18. :rtype: dict
  19. :return: A dict with the following structure, where each field
  20. may not be present if missing in original message:
  21. { 'message_id': msg_id,
  22. 'subject': subject,
  23. 'from': from,
  24. 'to': to,
  25. 'cc': cc
  26. }
  27. """
  28. msg_dict = {
  29. 'message_type': 'email',
  30. }
  31. if not isinstance(message, Message):
  32. if isinstance(message, unicode):
  33. # Warning: message_from_string doesn't always work
  34. # correctly on unicode, we must use utf-8 strings here :-(
  35. message = message.encode('utf-8')
  36. message = email.message_from_string(message)
  37. message_id = message['message-id']
  38. if not message_id:
  39. message_id = 'None'
  40. msg_dict['message_id'] = message_id
  41. if message.get('Subject'):
  42. msg_dict['subject'] = decode(message.get('Subject'))
  43. # Envelope fields not stored in mail.message but made available
  44. # for message_new()
  45. msg_dict['from'] = decode(message.get('from'))
  46. msg_dict['to'] = decode(message.get('to'))
  47. msg_dict['cc'] = decode(message.get('cc'))
  48. msg_dict['email_from'] = decode(message.get('from'))
  49. return msg_dict
  50. @api.model
  51. def message_process(self, model, message, custom_values=None,
  52. save_original=False, strip_attachments=False,
  53. thread_id=None):
  54. if isinstance(message, xmlrpclib.Binary):
  55. message = str(message.data)
  56. # Warning: message_from_string doesn't always work correctly on
  57. # unicode, we must use utf-8 strings here :-(
  58. if isinstance(message, unicode):
  59. message = message.encode('utf-8')
  60. msg_txt = email.message_from_string(message)
  61. msg = self.message_parse_basic_data(msg_txt)
  62. _logger.info(
  63. 'Fetched mail from %s to %s with Message-Id %s',
  64. msg.get('from'), msg.get('to'), msg.get('message_id'))
  65. return super(MailThread, self).message_process(
  66. model, message, custom_values=custom_values,
  67. save_original=save_original,
  68. strip_attachments=strip_attachments, thread_id=thread_id)