From 0d2431d18f97782fed5c9bf50007073e0c19b66f Mon Sep 17 00:00:00 2001 From: Hadrien Huvelle Date: Thu, 19 Dec 2024 00:38:23 +0100 Subject: [PATCH] Try to reorder parts --- mail_embed_image/models/ir_mail_server.py | 33 ++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/mail_embed_image/models/ir_mail_server.py b/mail_embed_image/models/ir_mail_server.py index ede5261471..c59fed363a 100644 --- a/mail_embed_image/models/ir_mail_server.py +++ b/mail_embed_image/models/ir_mail_server.py @@ -6,7 +6,7 @@ import uuid from base64 import b64encode from email.mime.image import MIMEImage - +from email.mime.multipart import MIMEMultipart import requests from lxml.html import fromstring, tostring @@ -58,12 +58,39 @@ def build_email( subtype_alternative=subtype_alternative, ) if fileparts: - for fpart in fileparts: - result.attach(fpart) # Multipart method MUST be multipart/related for CIDs embedding # Gmail and Office won't process the images otherwise if image_embedding_method == "cid": result.set_type("multipart/related") + + for fpart in fileparts: + result.attach(fpart) + + # after all part where added, we need to reorganize the parts + # before reorganisation, the parts are in this shape: + # - boundary 1 + # - text/plain + # - text/html + # - image/png + # After, the parts are in this shape: + # - boundary 1 + # - multipart/alternative + # - boundary 2 + # - text/plain + # - text/html + # - image/png + + # maybe I could user: result.make_alternative() / result.make_related() + alternative = MIMEMultipart('alternative') + all_parts = [alternative] + for part in result.iter_parts(): + print(part.get_content_type()) + if part.get_content_type() in ["text/html", "text/plain"]: + alternative.attach(part) + else: + all_parts.append(part) + result.set_payload(all_parts) + return result def _build_email_replace_img_src(self, html_body):