So my goal here is to be able to mail html file as content body instead of attachments. The html file I am dealing with has embedded images. The reason I am taking this approach is, that the html file is subject to changes again. The following is the code
from email.mime.text import MIMEText
from email.MIMEImage import MIMEImage
from email.mime.multipart import MIMEMultipart
import smtplib
from bs4 import BeautifulSoup
from os.path import basename, splitext
fromaddr = "me@example.com"
toaddr = "myfriend@example.com"
html = open("Welcome_to_the_Environment.htm")
msg= MIMEMultipart('imageandtext')
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Automatic Weekly Report"
msgText = MIMEText(html.read(), 'html')
msg.attach(msgText)
my_html_string = html.read()
soup = BeautifulSoup(msg.as_string())
msgImage = [{}for img in soup.findAll('img')]
i=0
for img in soup.findAll('img'):
imgname = str(img['src'])
img['src'] = 'cid:' + splitext(basename(img['src']))[0]
fp = open("Welcome_to_the_Environment_files\\" + imgname, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
msgImage[i].add_header('Content-ID', (splitext(basename(img['src']))[0])
msg.attach(msgImage[i])
i=i+1
my_html_string = str(soup)
debug = False
if debug:
print(msg.as_string())
else:
server = smtplib.SMTP('smtp.example.com',5)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
But I am getting a syntax error at the line msg.attach(msgImage[i]). Is it because I am attaching the image inside a loop? Or am I doing something else wrong?