Reputation: 27107
I found this snippet in the official examples
if maintype == 'text':
fp = open(path)
# Note: we should handle calculating the charset
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()
# Encode the payload using Base64
encoders.encode_base64(msg)
I need exactly this kind of feature: Add any kind of file to an email.
I want to avoid this long if-elif-elif part, since it looks redundant to me.
Is there no generic way of attaching any kind of data to an email?
In my case "all kind of data" means:
mimetypes.guess_type()
Upvotes: 4
Views: 211
Reputation: 9763
Is there no generic way of attaching any kind of data to an email?
You can get rid of the first cases and only keep MIMEBase
, which is the base (ie. generic) class for MIME types.
The first cases are only examples of what you can do if you want specific handling for some types.
Upvotes: 2