[英]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.