Python将内联图像添加到多部分/替代电子邮件
Posted
技术标签:
【中文标题】Python将内联图像添加到多部分/替代电子邮件【英文标题】:Python Add Inline Images to multipart/alternative emails 【发布时间】:2020-06-16 05:53:38 【问题描述】:将内联附件添加到电子邮件正文时,它们不会与下面的代码一起显示。
from email.message import EmailMessage
from email.mime.image import MIMEImage
msg = EmailMessage()
msg["From"] = "Test@example.com"
msg["To"] = "Test1@example.com"
msg["Subject"] = "Test Email"
plain_text, html_message = # Plain Text and HTML email content created
msg.set_content(plain_text)
msg.add_alternative(html_message, subtype='html')
# adding the inline image to the email
with open('logo.png', 'rb') as img:
logo = MIMEImage(img.read())
logo.add_header('Content-ID', f'<connect_logo_purple>')
logo.add_header('X-Attachment-Id', 'connect_logo_purple.png')
logo['Content-Disposition'] = f'inline; filename=connect_logo_purple.png'
msg.attach(logo)
但是在add_attachment
之后添加内联附件时会显示。
# ... Create message like above
msg.set_content(plain_text)
msg.add_alternative(html_message, subtype='html')
# Only when an attachment is added does the inline images show up
msg.add_attachment(
#..details filled in
)
# .. continue with inline image
with open('logo.png', 'rb') as img:
logo = MIMEImage(img.read())
logo.add_header('Content-ID', f'<connect_logo_purple>')
logo.add_header('X-Attachment-Id', 'connect_logo_purple.png')
logo['Content-Disposition'] = f'inline; filename=connect_logo_purple.png'
msg.attach(logo)
【问题讨论】:
【参考方案1】:我发现当调用add_attachment 命令时,它会将电子邮件的payload
更新为multipart/mixed
,以便修复它...
# ... Create message like above
msg.set_content(plain_text)
msg.add_alternative(html_message, subtype='html')
# When there isn't a call to add_attachment...
with open('logo.png', 'rb') as img:
logo = MIMEImage(img.read())
logo.add_header('Content-ID', f'<connect_logo_purple>')
logo.add_header('X-Attachment-Id', 'connect_logo_purple.png')
logo['Content-Disposition'] = f'inline; filename=connect_logo_purple.png'
# Make the EmailMessage's payload `mixed`
msg.get_payload()[1].make_mixed() # getting the second part because it is the HTML alternative
msg.get_payload()[1].attach(logo)
【讨论】:
以上是关于Python将内联图像添加到多部分/替代电子邮件的主要内容,如果未能解决你的问题,请参考以下文章
您可以将内联 base64 编码图像添加到 Mandrill 模板吗?
使用 c# windows 应用程序在电子邮件正文中添加多个图像(内联)