7

I have an image in a .png file. I am trying to embed this image in the body of an email using Python. I tried various options available on the internet, but they provided solutions for attaching the files rather than embedding in the email body itself.

Here's my code snippet. I am attaching a file and trying to add the image in the email body (which is actually attaching html file rather than adding image to email body). Is it possible in Python to embed an image in the email body?

def send_report(send_from, send_to, subject, text, files=[], server="10.70.70.100",html=True):
#assert isinstance(send_to, list)
#assert isinstance(files, list)

msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject

if (html):
    part1 = MIMEText(text, 'html')
    msg.attach(part1)
else:
    msg.attach( MIMEText(text) )

for f in files:
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(f,"rb").read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
    msg.attach(part)

#Trying to embed image in email body
img_data = open('a.png', 'rb').read()
html_part = MIMEMultipart(_subtype='related')
body = MIMEText('<p>Hello <img src="cid:myimage" /></p>', _subtype='html')
html_part.attach(body)

img = MIMEImage(img_data, 'png')
img.add_header('Content-Id', '<myimage>')  # angle brackets are important
img.add_header("Content-Disposition", "inline", filename="myimage") 
html_part.attach(img)
msg.attach(html_part)

smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
Andrew Myers
  • 2,754
  • 5
  • 32
  • 40
dhd
  • 71
  • 1
  • 3
  • Did you try with embedded in html ? Have a look here at the second answer http://stackoverflow.com/questions/19171742/send-e-mail-to-gmail-with-inline-image-using-python –  Mar 03 '16 at 23:00
  • I am giving the below line in my code. That adds the image in the html body. body = MIMEText('

    Hello

    ', _subtype='html')
    – dhd Mar 03 '16 at 23:33
  • 1
    I would test a sample before spending more time on the coding, because support for CID embedding is not great (e.g. send to a Gmail App on android, Yahoo, Outlook.com, Outlook desktop). And it's not just that it might get blocked by default, but it might actually not display at all. Furthermore, Gmail has a 101kb limit for emails, so this is a very fast way of ensuring your email has a "click here to read more" link that is very annoying for users. – Nathan May 13 '20 at 06:40

0 Answers0