【问题标题】:Python Add Inline Images to multipart/alternative emailsPython将内联图像添加到多部分/替代电子邮件
【发布时间】: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)

【问题讨论】:

    标签: python standard-library


    【解决方案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)
    
    

    【讨论】:

      猜你喜欢
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 2014-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-23
      相关资源
      最近更新 更多