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.1 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 import etree
from base64 import b64encode
from email.mime.base import MIMEBase
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[@src^='http']"):
src = img.get('src')
content = requests.get(src).content
content_base64 = b64encode(content)
cid = uuid.uuid4().hex
filename_rfc2047 = encode_header_param(cid)
part = MIMEBase('application', 'octet-stream')
part.set_param('name', filename_rfc2047)
part.add_header(
'Content-Disposition',
'attachment',
cid=cid,
filename=filename_rfc2047,
content=content_base64,
)
part.set_payload(content)
Encoders.encode_base64(part)
result.attach(part)
img.set('src', 'cid:%s' % (cid))
msg.set_payload(etree.tostring(root))
_build_email_replace_img_src(result, attachments)
return result