使用Python从Outlook 2010获取附件

时间:2014-05-16 16:32:28

标签: python-2.7 outlook-2010 pywin32 win32com

我有以下脚本,它试图从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'))

当我运行它时,我得到以下内容:

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

我不确定在哪里放置用户名来实现此功能。

我在下面的答案中尝试了这个建议,并收到以下错误:

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)

我希望包含我已完成的工作代码,以防其他人发现它有用:

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)

1 个答案:

答案 0 :(得分:4)

GetDefaultFolder未在应用程序对象上定义(请参阅application docs),它是在您通过的NameSpace对象上定义的

mapi = outlook.GetNameSpace("MAPI")

然后

inbox = mapi.GetDefaultFolder(0)

我认为你也可以使用

mapi = outlook.Session

而不是GetNameSpace