HEX
Server: Apache/2.4.63 (Unix)
System: Linux TOMS-220NAS 4.4.302+ #86009 SMP Wed Nov 26 18:19:17 CST 2025 x86_64
User: flavio87 (1026)
PHP: 8.3.27
Disabled: NONE
Upload Files
File: /volume1/@appstore/SynologyApplicationService/tools/convert_inline_image_email_to_multipart.py
# Copyright (c) 2000-2025 Synology Inc. All rights reserved

import sys
import re
import base64
import argparse
from email.message import EmailMessage

def make_multipart_from_html_with_inline_images(html_content: str) -> str:
    msg = EmailMessage()
    msg.set_type('multipart/mixed')

    # Regex pattern to match <img src="data:image/...">
    img_pattern = r'<img[^>]+src=["\'](data:image/(png|jpeg|jpg|gif);base64,([^"\']+))["\'][^>]*>'
    cid_count = 0
    modified_html = html_content

    for match in re.finditer(img_pattern, html_content):
        full_data_uri = match.group(1)
        image_type = match.group(2)
        base64_data = match.group(3)

        img_binary = base64.b64decode(base64_data)
        cid = f'synosasimage{cid_count}'

        # turn src= into cid:
        modified_html = modified_html.replace(full_data_uri, f'cid:{cid}', 1)

        # add extracted inline image
        maintype = 'image'
        subtype = image_type
        extracted_img = EmailMessage()
        extracted_img.set_content(img_binary, maintype=maintype, subtype=subtype, cid=cid, filename=f'{cid}.{subtype}')
        msg.attach(extracted_img)

        cid_count += 1

    # add the html whose inline images are all now extracted
    html_part = EmailMessage()
    html_part.set_content(modified_html, subtype='html')
    msg.attach(html_part)

    return msg.as_string()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Process HTML content.")
    parser.add_argument('--html-content', type=str, help='HTML content string')
    args = parser.parse_args()

    if args.html_content:
        result = make_multipart_from_html_with_inline_images(args.html_content)
        print(result)
        sys.exit(0)
    else:
        print("Please provide --html-content", file=sys.stderr)
        sys.exit(1)