I found this snippet in official examples
if maintype == 'text':
fp = open(path)
msg = MIMEText(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'image':
fp = open(path, 'rb')
msg = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'audio':
fp = open(path, 'rb')
msg = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open(path, 'rb')
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
fp.close()
encoders.encode_base64(msg)
I need exactly this function: add any file to the email.
I want to avoid this long part of if-elif-elif, as it looks redundant to me.
Is there a general way to connect any data to email?
In my case, “all kinds of data” means:
- The file is less than two megabytes long.
- Mime type can be guessed
mimetypes.guess_type()
source
share