1
votes

EDIT : SOLVED IT!

I added this snippet of code below, in order to trace the position of the main inbox folder

for folder in outlook.Folders: print(folder)

This highlighted that something had changed within the underlying Outlook structure and Folder[0] was no longer valid. I will now tweak code to make it more robust and dynamically choose folder

END EDIT

I wrote some code to pull emails from Outlook and save the attachments. It worked perfectly up until a few days ago.

I had not touched the code, so I can only assume that something within Outlook has changed. I work in a corporate environment, so there is remote update of software.

Does anybody have any idea what this error means and why its suddenly cropped up ? I am very bleak, as the code worked so well before this hiccup. Alternatively, any better way to retrieve emails and attachments from Outlook, using Python ?

import win32com.client


def main():
    pass


def saveAttachments():
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")  # Opens Microsoft Outlook
    mailbox = outlook.Folders[0]  # Based off email address
    inbox = mailbox.Folders["Inbox"]
    emails = inbox.Items
    emails.Sort("[ReceivedTime]", True)

    destPath = "\\\\servername\\path\\"

    try:
        for mail in emails:
            if ("Detailed MTM," in mail.subject) and (mail.Attachments.Count > 0):
                print(mail.Sender)
                print(mail.Subject)
                print(mail.Receivedtime)
                attachments = mail.Attachments
                for file in attachments:
                    if "MTMDetailed" in str(file):
                        file.SaveAsFile(destPath + str("MTMDetailed.xls"))
                break
    except:
        file = open(destPath + "error.log", "w")
        file.write("Problem")
        file.close()

if __name__ == '__main__':
    main()
    saveAttachments()

  File "C:\Tools\Python\lib\site-packages\win32com\client\dynamic.py", line 256, in __getitem__
    return self._get_good_object_(self._oleobj_.Invoke(dispid, LCID, invkind, 1, index))
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The attempted operation failed.  An object could not be found.', None, 0, -2147221233), None)
1
Try changing .Folders[0] to .Folders[1]0m3r
Afraid no luck, still crashes.Hiro
An obvious question - is \\servername\path\ accessible?Dmitry Streblechenko

1 Answers

0
votes

I added code to iterate through the outlook.Folders to find the one I need, without relying on specific hardcoded position