Embed picture in email

You are going through royal pains to construct a valid MIME message in msg, then ditching it and sending a simple string email_message instead.

You should probably begin by understanding what the proper MIME structure looks like. A multipart message by itself has no contents at all, you have to add a text part if you want a text part.

The following is an edit of your script with the missing pieces added. I have not attempted to send the resulting message. However, see below for a modernized version.

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText  # Added
from email.mime.image import MIMEImage

attachment="bob.jpg"

msg = MIMEMultipart()
msg["To"] = to_addr
msg["From"] = from_addr
msg["Subject"] = subject

msgText = MIMEText('<b>%s</b><br/><img src="cid:%s"/><br/>' % (body, attachment), 'html')   
msg.attach(msgText)   # Added, and edited the previous line

with open(attachment, 'rb') as fp:
    img = MIMEImage(fp.read())
img.add_header('Content-ID', '<{}>'.format(attachment))
msg.attach(img)

print(msg.as_string()) # or go ahead and send it

(I also cleaned up the HTML slightly.)

Since Python 3.6, Python’s email library has been upgraded to be more modular, logical, and orthogonal (technically since 3.3 already really, but in 3.6 the new version became the preferred one). New code should avoid the explicit creation of individual MIME parts like in the above code, and probably look more something like

from email.message import EmailMessage
from email.utils import make_msgid

attachment="bob.jpg"

msg = EmailMessage()
msg["To"] = to_addr
msg["From"] = from_addr
msg["Subject"] = subject

attachment_cid = make_msgid()

msg.set_content(
    '<b>%s</b><br/><img src="cid:%s"/><br/>' % (
        body, attachment_cid[1:-1]), 'html')

with open(attachment, 'rb') as fp:
    msg.add_related(
        fp.read(), 'image', 'jpeg', cid=attachment_cid)

# print(msg.as_string()), or go ahead and send

You’ll notice that this is quite similar to the “asparagus” example from the email examples documentation in the Python standard library.

Leave a Comment