Getting Attachments From Outlook 2010 With Python
outlook-2010, python-2.7, pywin32, win32com
Solution
The `GetDefaultFolder` is not defined on the application object (see application docs), it is defined on the `NameSpace` object which you get via
mapi = outlook.GetNameSpace("MAPI")
Then
inbox = mapi.GetDefaultFolder(0)
I think you can also use
mapi = outlook.Session
instead of `GetNameSpace`.
Problem
I have the following script, which is trying to get attachments from Outlook. ``` outlook = win32com.client.Dispatch("Outlook.Application") inbox = outlook.GetDefaultFolder(0) messages = inbox.Items message = messages.GetLast() #open last message attachments = message.Attachments #assign attachments to attachment variable attachment = attachments.Item(1) attachment.SaveASFile(os.path.join('c:', 'temp')) ``` When I run it however I am getting the following: ``` Traceback (most recent call last): File "C:/Users/e003048/QA/trunk/automation/selenium/src/global_functions/util_get_email_attachments.py", line 11, in <module> inbox = outlook.GetDefaultFolder(0) File "C:\Python27\Lib\site-packages\win32com\client\dynamic.py", line 522, in __getattr__ raise AttributeError("%s.%s" % (self._username_, attr)) AttributeError: Outlook.Application.GetDefaultFolder ``` I am unsure where I would put the username to get this to work. I tried the suggestion in the answer below and am getting the following error: ``` Traceback (most recent call last): File "C:/Users/e003048/QA/trunk/automation/selenium/src/global_functions/util_get_email_attachments.py", line 10, in <module> inbox = mapi.GetDefaultFolder(0) File "<COMObject <unknown>>", line 2, in GetDefaultFolder pywintypes.com_error: (-2147024809, 'The parameter is incorrect.', None, None) ``` I wanted to include my completed working code in-case anyone else will find it useful: ``` def get_email_attachments(self): outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace('MAPI') # change the Folders parameter to the directory you are having the attachment go to inbox = outlook.GetDefaultFolder(6).Folders('ForAttachments') messages = inbox.Items message = messages.GetLast() # opens the last message attachments = message.Attachments attachment = attachments.Item(1) attachment.SaveAsFile('C:\\temp\\' + attachment.FileName) ```