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.

87 lines
3.2 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 Lorenzo Battistini - Agile Business Group
  3. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
  4. import logging
  5. from odoo import models, api, tools, _
  6. _logger = logging.getLogger(__name__)
  7. class MailThread(models.AbstractModel):
  8. _inherit = 'mail.thread'
  9. @api.model
  10. def notify_bounce_partners(self, message, fetchmail, message_dict):
  11. message_id = message.get('Message-Id')
  12. email_from = tools.decode_message_header(message, 'From')
  13. email_from_localpart = (
  14. (
  15. tools.email_split(email_from) or ['']
  16. )[0].split('@', 1)[0].lower()
  17. )
  18. # same criteria used by odoo
  19. # see addons/mail/models/mail_thread.py
  20. if (
  21. message.get_content_type() == 'multipart/report' or
  22. email_from_localpart == 'mailer-daemon'
  23. ):
  24. references = tools.decode_message_header(message, 'References')
  25. in_reply_to = tools.decode_message_header(
  26. message, 'In-Reply-To').strip()
  27. thread_references = references or in_reply_to
  28. msg_references = [
  29. ref for ref in
  30. tools.mail_header_msgid_re.findall(thread_references) if
  31. 'reply_to' not in ref
  32. ]
  33. MailMessage = self.env['mail.message']
  34. mail_messages = MailMessage.sudo().search([
  35. ('message_id', 'in', msg_references)], limit=1)
  36. recipients = mail_messages.mapped('author_id')
  37. recipients |= fetchmail.bounce_notify_partner_ids
  38. if not recipients:
  39. _logger.info(
  40. 'Not notifying bounce email from %s with Message-Id %s: '
  41. 'no recipients found',
  42. email_from, message_id
  43. )
  44. return
  45. _logger.info(
  46. 'Notifying bounce email from %s with Message-Id %s',
  47. email_from, message_id
  48. )
  49. email = self.env['mail.mail'].create({
  50. 'body_html': (
  51. u"%s<br/><br/><br/>%s<br/><br/>%s"
  52. % (
  53. unicode(message_dict['body'], errors='replace'),
  54. _("Raw message:"),
  55. unicode(message.__str__(), errors='replace').replace(
  56. "\n", "<br/>")
  57. )),
  58. 'subject': message_dict['subject'],
  59. 'recipient_ids': [
  60. (6, 0, [p.id for p in recipients])
  61. ]
  62. })
  63. email.send()
  64. @api.model
  65. def message_route(
  66. self, message, message_dict, model=None, thread_id=None,
  67. custom_values=None
  68. ):
  69. if self.env.context.get('fetchmail_server_id'):
  70. fetchmail = self.env['fetchmail.server'].browse(
  71. self.env.context['fetchmail_server_id'])
  72. self.notify_bounce_partners(message, fetchmail, message_dict)
  73. return super(MailThread, self).message_route(
  74. message=message, message_dict=message_dict, model=model,
  75. thread_id=thread_id, custom_values=custom_values
  76. )