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()
Hello![]()
', _subtype='html') – dhd Mar 03 '16 at 23:33