When adding inline attachments to the email body they are not displayed with the code below.
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 when the inline attachment is added after add_attachment it is displayed.
# ... 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)
What I found is when the add_attachment command is called it updates the email's payload to be multipart/mixed so to fix it...
# ... 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With