I would like to add multiple embedded images to the email body, which will be sent by the MIME library in Python. Currently, I am using the code below:
msg = MIMEMultipart()
msg['From'] = 'from@domain.com'
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = '{} - {}'.format('test', formatdate(localtime=True))
msg['To'] = to@domain.com
msg['Cc'] = cc@domain.com
text = MIMEText('first text<br>', _subtype='html', _charset='windows-1255')
msg.attach(text)
for i in range(len(img_paths)):
text = MIMEText('<img src="cid:image{}"><br>'.format(i), _subtype='html', _charset='windows-1255')
msg.attach(text)
with open(img_paths[i], 'rb') as f:
msgImage = MIMEImage(f.read())
msgImage.add_header('Content-ID', '<image{}>'.format(i))
msg.attach(msgImage)
smtp = smtplib.SMTP('localhost')
smtp.sendmail('from@domain.be', to@domain.com, msg.as_string())
smtp.close()
It works fine for sending emails. However, the images that created by loop are sent as attachment, not embedded. How can I embed the images created dynamically?
I came across this question: How to add multiple embedded images to an email in Python? but in that example the number of images are set. It is not determined that how many images are in img_paths
list In my case, so I have to create cid
s dynamically unlike the answer that given to question.