0

I'm trying to embed images inline in an email. The problem is, when I send the email, the images appear as attachments instead of being inline. How can I fix this?

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

COMMASPACE = ', ' 

# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
me = "sender@email.com"
family = ["recipient1@email.com", "recipient2@email.com"]
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Preamble'

html = """\
<h1>Read this email header!</h1>
"""

# image
logo = "image1.png"
fp = open(logo, 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)

# body text
text = "<i>Read this text!</i>"
bodytext = MIMEText(text, 'html')
msg.attach(bodytext)
wwl
  • 2,025
  • 2
  • 30
  • 51

1 Answers1

1

From the comments given above, the answer is as follows.

Add a header to the image (second last line in this code block):

# image
logo = "image1.png"
fp = open(logo, 'rb')
img = MIMEImage(fp.read())
fp.close()
img.add_header('Content-ID', '<image>')
msg.attach(img)

For the text, add an image tag with attribute src corresponding to what you modified. Note that cid is short for Content-ID. Also note that the content id must be enclosed in angle brackets.

# body text
text = "<img src="cid:image"><i>Read this text!</i>"
bodytext = MIMEText(text, 'html')
msg.attach(bodytext)
James Brusey
  • 355
  • 3
  • 11
wwl
  • 2,025
  • 2
  • 30
  • 51