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.

89 lines
3.2 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 Therp BV <https://therp.nl>
  3. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  4. import requests
  5. import uuid
  6. from odoo import models
  7. from odoo.addons.base.ir.ir_mail_server import encode_header_param
  8. from lxml.html.soupparser import fromstring
  9. from lxml import etree
  10. from lxml.etree import tostring
  11. from base64 import b64encode
  12. from email.mime.image import MIMEImage
  13. from email import Encoders
  14. class IrMailServer(models.Model):
  15. _inherit = 'ir.mail_server'
  16. def build_email(
  17. self,
  18. email_from,
  19. email_to,
  20. subject,
  21. body,
  22. email_cc=None,
  23. email_bcc=None,
  24. reply_to=None,
  25. attachments=None,
  26. message_id=None,
  27. references=None,
  28. object_id=None,
  29. subtype='plain',
  30. headers=None,
  31. body_alternative=None,
  32. subtype_alternative='plain'):
  33. result = super(IrMailServer, self).build_email(
  34. email_from,
  35. email_to,
  36. subject,
  37. body,
  38. email_cc=email_cc,
  39. email_bcc=email_bcc,
  40. reply_to=reply_to,
  41. attachments=attachments,
  42. message_id=message_id,
  43. references=references,
  44. object_id=object_id,
  45. subtype=subtype,
  46. headers=headers,
  47. body_alternative=body_alternative,
  48. subtype_alternative=subtype_alternative,
  49. )
  50. def _build_email_replace_img_src(msg, attachments):
  51. """ Given a message, find it's img tags and if they
  52. are URLs, replace them with cids.
  53. :param msg: A email.message.Message
  54. """
  55. if msg.is_multipart():
  56. for part in msg.get_payload():
  57. _build_email_replace_img_src(part, attachments)
  58. else:
  59. if msg.get_content_subtype() == 'html':
  60. body = msg.get_payload(decode=True)
  61. root = fromstring(body)
  62. for img in root.xpath(
  63. "//img[starts-with(@src, '/web/image')]"):
  64. base_url = self.env['ir.config_parameter'].get_param(
  65. 'web.base.url')
  66. src = base_url + img.get('src')
  67. response = requests.get(src)
  68. cid = uuid.uuid4().hex
  69. filename_rfc2047 = encode_header_param(cid)
  70. part = MIMEImage(response.content)
  71. part.set_param('name', filename_rfc2047)
  72. part.add_header(
  73. 'Content-Disposition',
  74. 'inline',
  75. cid=cid,
  76. filename=filename_rfc2047,
  77. )
  78. part.set_payload(response.content)
  79. Encoders.encode_base64(part)
  80. result.attach(part)
  81. img.set('src', 'cid:%s' % (cid))
  82. msg.set_payload(b64encode(tostring(root)))
  83. _build_email_replace_img_src(result, attachments)
  84. return result