将内嵌附件添加到电子邮件正文时,它们不会与下面的代码一起显示。
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)
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)