繁体   English   中英

python html EmailMessage 奇怪的字符

[英]python html EmailMessage strange characters

我正在基于模板文件生成 email。 加载 HTML 时,格式没问题,只要我将其加载到 msg object 中,就会添加一些奇怪的字符。

    try: 
        with open(f'{SCRIPT_ASSET_PATH}email_template_{args.lang}.txt') as f:
            html_data=f.read().replace("templateCustomer",args.customer).replace("templateCode",str(demo_code)).replace("templateFullName",USER_FULLNAME).replace("templateBusinessTitle",USER_BUSINESS_TITLE).replace("templateImage",'<img src="cid:{image_cid}"></img>'.format(image_cid=image_cid[1:-1]))
    except FileNotFoundError: 
        print_fail(f"ERROR loading email template, WILL NOT prepare email. Check if email_template_{args.lang}.txt is in assets folder")
        return False
    print(html_data) # here it is fine
    msg = EmailMessage()
    msg['Subject'] = "Demo access"
    msg['From'] = settings["userEmail"]
    msg['To'] = "fillin@customerdomain.com"
    msg.make_alternative() 
    msg.add_alternative(html_data, subtype='html') # something happens here

msg._payload中现在添加了一些随机字符(普通字母、等号等),例如"3D" : href=3D"www.mylink.com"

为什么会这样? 它似乎与我需要专门编码的 HTML 特定字符无关。 在示例中,将“list=d”添加到不包含特殊字符的简单字符串“products”中:

  • 您现在可以使用下面列出的产品试用该用例。
  • 变成

  • 您现在可以尝试使用下面列出的产品的用例。
  • 找到处理这个问题的正确方法真的很棘手。 周围也有很多答案,但是一旦修复了某些问题,就会出现其他问题(图像嵌入不起作用,超链接有问题等)

    我现在设法通过以下方式解决它:

    cid=str(uuid.uuid4())
        try: 
            with open(f'{SCRIPT_ASSET_PATH}email_template_{args.lang}.txt') as f:
                html_data=f.read().replace("templateImage",'<img src="cid:{image_cid}"></img>'.format(image_cid=cid))
                html_data = html_data.encode("ascii", "xmlcharrefreplace") # this repairs any broken special characters in the mail
    
        except FileNotFoundError: 
            print_fail(f"ERROR loading email template, WILL NOT prepare email. Check if email_template_{args.lang}.txt is in scriptfolder")
            return False
    
        msg = MIMEMultipart('related') # nearly every other post pointed me to "alternative" but alternative broke the image embedding
        msg['Subject'] = "Demo access"
        msg['From'] = settings["userEmail"]
        msg['To'] = "fillin@customerdomain.com"
        text = "Automatic demo email did not work as expected, please contact us."
    
    
        outfile_name = f"{assets_path}email_template.eml"
        part1 = MIMEText(text, 'plain')
        part2 = MIMEText(html_data, 'html', 'utf-8')
        msg.attach(part1)
        msg.attach(part2)
        with open(f'{assets_path}merged.jpg', 'rb') as img:
            mime = MIMEBase('image', 'jpg', filename='merged.jpg')
            mime.add_header('Content-Disposition', 'attachment', filename='merged.jpg')
            mime.add_header('X-Attachment-Id', cid)
            mime.add_header('Content-ID', f'<{cid}>')
            mime.set_payload(img.read())
            encoders.encode_base64(mime)
            msg.attach(mime)
    
        with open(outfile_name, 'w') as outfile:
            gen = Generator(outfile)
            gen.flatten(msg=msg)
    

    暂无
    暂无

    声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM