Creating an appropriate MIME application with Python

I found this snippet in 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 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()
+4
source share
1 answer

Is there a general way to connect any data to email?

You can get rid of the first cases and save MIMEBase, which is the base (i.e. general) class for MIME types.

- , , .

+2

Source: https://habr.com/ru/post/1659747/


All Articles