Python Forum

Full Version: Trying to determine attachment file type before saving off..
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So i have the following code in order to save email attachments from emails within a folder.. and cant seem to figure out how to check the attachment type before i download it..

so my whole logic works great, but yesterday i ran into situations where there were emails in the folder (#1 that shouldn't be in there) that had more than 2 attachments, but they were something other than CSV's, so i would like to check the attachment type before i just assume its the files i need to download.

I found a few examples, that use content_type and get_content_type() and stuff like that, but none of those work or even exist for my attachment class im using below..

Im using Spyder(python 3.9) to write and run this, is there any shortcut to present me with all available properties for a class? Like intellisense that is in Visual Studio? (all preferences are enabled and work sometimes, but not sure if it works because those classes have something to show and what im trying does not)

Right now, if there are 3 files and all of them are say jpg, it will download the first 2 and i dont need or want that..

    # THIS ENSURES THAT THE EMAIL HAS AT LEAST 2 ATTACHMENTS BEFORE IT TRIES TO DOWNLOAD FILES THAT DONT EXIST
    # NEED TO FIND A WAY TO ONLY CARE IF THE ATTACHMENTS ARE CSV FILES AND NOTHING ELSE.
    if attachments.count > 2:

        attachment1 = attachments.Item(1)
        attachment_name1 = str(attachment1).lower()
        p1 = Path(attachment_name1)
        newName1 = "{0}_{1}{2}".format(p1.stem,dtappend,p1.suffix)
        
        attachment1.SaveASFile("F:\Attachments"+ '\\' + newName1)
        
        attachment2 = attachments.Item(2)
        attachment_name2 = str(attachment2).lower()
        p2 = Path(attachment_name2)
        newName2 = "{0}_{1}{2}".format(p2.stem,dtappend,p2.suffix)
        
        attachment2.SaveASFile("F:\Attachments"+ '\\' + newName2)
Found a solution that seems to work and do the job..

    # THIS ENSURES THAT THE EMAIL HAS AT LEAST 2 ATTACHMENTS BEFORE IT TRIES TO DOWNLOAD FILES THAT DONT EXIST
    # NEED TO FIND A WAY TO ONLY CARE IF THE ATTACHMENTS ARE CSV FILES AND NOTHING ELSE.
    if attachments.count >= 2:

        for att in attachments:
            p = Path(str(att).lower())
            newName = "{0}_{1}{2}".format(p.stem,dtappend,p.suffix)
            if p.suffix == ".csv":
                att.SaveASFile("F:\attachments"+ '\\' + newName)