Python将嵌入式图像添加到多部分/替代电子邮件中

问题描述 投票:0回答:1

将内嵌附件添加到电子邮件正文时,它们不会与下面的代码一起显示。

from email.message import EmailMessage
from email.mime.image import MIMEImage
msg = EmailMessage()
msg["From"] = "[email protected]"
msg["To"] = "[email protected]"
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)

<< [BUT在显示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个回答
0
投票
我发现是在调用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)

© www.soinside.com 2019 - 2024. All rights reserved.