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.
88 lines
3.2 KiB
88 lines
3.2 KiB
# -*- coding: utf-8 -*-
|
|
# Copyright 2019 Therp BV <https://therp.nl>
|
|
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
|
|
import requests
|
|
import uuid
|
|
from odoo import models
|
|
from odoo.addons.base.ir.ir_mail_server import encode_header_param
|
|
from lxml.html.soupparser import fromstring
|
|
from lxml.etree import tostring
|
|
from base64 import b64encode
|
|
from email.mime.image import MIMEImage
|
|
from email import Encoders
|
|
|
|
|
|
class IrMailServer(models.Model):
|
|
_inherit = 'ir.mail_server'
|
|
|
|
def build_email(
|
|
self,
|
|
email_from,
|
|
email_to,
|
|
subject,
|
|
body,
|
|
email_cc=None,
|
|
email_bcc=None,
|
|
reply_to=None,
|
|
attachments=None,
|
|
message_id=None,
|
|
references=None,
|
|
object_id=None,
|
|
subtype='plain',
|
|
headers=None,
|
|
body_alternative=None,
|
|
subtype_alternative='plain'):
|
|
result = super(IrMailServer, self).build_email(
|
|
email_from,
|
|
email_to,
|
|
subject,
|
|
body,
|
|
email_cc=email_cc,
|
|
email_bcc=email_bcc,
|
|
reply_to=reply_to,
|
|
attachments=attachments,
|
|
message_id=message_id,
|
|
references=references,
|
|
object_id=object_id,
|
|
subtype=subtype,
|
|
headers=headers,
|
|
body_alternative=body_alternative,
|
|
subtype_alternative=subtype_alternative,
|
|
)
|
|
|
|
def _build_email_replace_img_src(msg, attachments):
|
|
""" Given a message, find it's img tags and if they
|
|
are URLs, replace them with cids.
|
|
|
|
:param msg: A email.message.Message
|
|
"""
|
|
if msg.is_multipart():
|
|
for part in msg.get_payload():
|
|
_build_email_replace_img_src(part, attachments)
|
|
else:
|
|
if msg.get_content_subtype() == 'html':
|
|
body = msg.get_payload(decode=True)
|
|
root = fromstring(body)
|
|
for img in root.xpath(
|
|
"//img[starts-with(@src, '/web/image')]"):
|
|
base_url = self.env['ir.config_parameter'].get_param(
|
|
'web.base.url')
|
|
src = base_url + img.get('src')
|
|
response = requests.get(src)
|
|
cid = uuid.uuid4().hex
|
|
filename_rfc2047 = encode_header_param(cid)
|
|
part = MIMEImage(response.content)
|
|
part.set_param('name', filename_rfc2047)
|
|
part.add_header(
|
|
'Content-Disposition',
|
|
'inline',
|
|
cid=cid,
|
|
filename=filename_rfc2047,
|
|
)
|
|
part.set_payload(response.content)
|
|
Encoders.encode_base64(part)
|
|
result.attach(part)
|
|
img.set('src', 'cid:%s' % (cid))
|
|
msg.set_payload(b64encode(tostring(root)))
|
|
_build_email_replace_img_src(result, attachments)
|
|
return result
|