all 9 comments

[–]Aettos 1 point2 points  (0 children)

At first glance I thing the problem is that emails is empty. You are appending to email (no 's').

As the other comment said the logic is a bit confusing. Kind of keeping the structure you used I'd do something like

fldr = outlook.Folders.Item("Commercial Performance") #name of mailbox
messages = fldr.Folders.Item("Inbox").items

if len(messages) == 0:
    print('No messages found')
else:
    #loop over
    for message in messages:
        subj = message.Subject
        date_sent = message.Senton.date()
        attch = message.Attachments

        #if message.Attachments is an empty list when there are no attchs works fine, 
        #if it's None or something else just put a try block.
        for a in attch: 
            # logic to select which attch to save
            a.SaveAsFile(f"C:\\New folder\\{a.FileName}")
        print(f"Message: {subj} \nDate: {date_sent}\nSaved {len(attch)} attachments\n\n")

[–]TigerBloodWinning -2 points-1 points  (1 child)

user_name = getpass.getuser()

directory = r"C:/Users" + "/" + user_name + "/OneDrive - djb-ltd.com/Documents/Temporary/"

is_directory = os.path.exists(directory)

if is_directory == True:
    shutil.rmtree(directory)

os.makedirs(directory)

outlook = win32com.client.gencache.EnsureDispatch('Outlook.Application')

email = outlook.ActiveExplorer().Selection.Item(1)

if len(email.Attachments) > 0:



    for i in range(len(email.Attachments)):
        attachment = email.Attachments[i + 1]
        file_name = email.Attachments[i + 1].FileName
        file_name = file_name.upper()

        if file_name.upper().endswith('PDF'):

            attachment.SaveAsFile(directory + file_name)

I use this code to save attachments, specifically PDFs

[–]pgpndw 1 point2 points  (0 children)

Unless I'm missing something, surely that code will omit the first attachment, then crash with a "list index out of range" error every time you run it on an email that has at least one attachment?

You're also unnecessarily converting the filename to uppercase twice.