Search code examples
pythonemailoutlookimaplib

Using email python library to get attachment name doesn't work


here's what my message details looks like:

enter image description here

I used the following python code to get attached file name from this mail:

import email
mail = email.message_from_string(bytes.decode(email_body))
if mail.get_content_maintype() != 'multipart':
    continue
for part in mail.walk():
    if part.get_content_maintype() == 'multipart':
        continue
    if part.get('Content-Disposition') is None:
        continue
    fileName1 = part.get_filename()
    print(fileName1)

It prints None instead of the attachment name. Please Help!


Solution

  • If the only thing you want to do is extract the filename, you can use

    for part in mail.walk():
         if part.get_content_disposition() == 'attachment':
              fileName1 = part.get_filename()
    

    This way you are not messing with other parts of the message, only with the attachment(s).