Python从outlook下载附件,而不是通过每封电子邮件循环每个附件

时间:2018-04-05 00:38:37

标签: python email outlook automation win32com

此代码进入Outlook并下载每封电子邮件的附件。问题是它只下载(1)每封电子邮件。我需要它来下载所有电子邮件。 这是我的第一个程序,任何提示,建议表示赞赏。提前谢谢!

import win32com.client


outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") #Opens Microsoft Outlook
folder = outlook.Folders[3]            #N4 Invocie folder
subFolder = folder.Folders[5]          #N4 Invoice subfolder
subFolderMessages = subFolder.Items    #Invoice items object
message = subFolderMessages.GetFirst()

while True:
    subFolderItemAttachments = message.Attachments
    nbrOfAttachmentInMessage = subFolderItemAttachments.Count
    x = 1
    while x <= nbrOfAttachmentInMessage:
        attachment = subFolderItemAttachments.item(x)
        #Saves attachment to location
        attachment.SaveAsFile('C:\\Users\\kkim\\Desktop\\InvoiceOutlook' + '\\'+ str(attachment)) 
        break    
    message = subFolderMessages.GetNext()

2 个答案:

答案 0 :(得分:0)

循环时从附件中删除break

首先,while循环必须检查message变量!= null。

答案 1 :(得分:0)

这应该有效

import win32com.client


outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") #Opens Microsoft Outlook
folder = outlook.Folders[3]            #N4 Invocie folder
subFolder = folder.Folders[5]          #N4 Invoice subfolder
subFolderMessages = subFolder.Items    #Invoice items object
message = subFolderMessages.GetFirst()

for attachment in message.attachments:
    attachment.SaveAsFile('C:\\Users\\kkim\\Desktop\\InvoiceOutlook' + '\\'+ str(attachment))