下载电子邮件附件后停止while循环

2024-06-10 00:59:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经获得了下面的python代码,可以从outlook收件箱的子文件夹COC下载附件。代码工作正常,但在下载所有附件后不会停止。我怎样才能修好它


import win32com.client

import os

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inbox=outlook.GetDefaultFolder(6).folders("COC") # "6" refers to the index of a folder - in this case the inbox. You can change that number to reference

messages = inbox.Items

message = messages.GetFirst()

 

while True:

 

    try:

        print (message)

        attachments = message.Attachments

        attachment = attachments.Item(1)

        attachment.SaveASFile(os.getcwd() + '\\' + str(attachment)) #Saves to the attachment to current folder

        print (attachment)

        message = messages.GetNext()

 

    except:

        message = messages.GetNext()


Tags: theto代码importclientmessage附件attachment
3条回答

只要条件保持为真,while循环将永远继续运行。只需增加循环,以确保它在最后变为false。 例如,您可以在while循环上方设置变量状态并将其设置为true。。。。。 while循环的条件可以是whilestatus==true。 在循环结束时,将状态重新声明为==false

message.GetNext()方法指示不再有消息时,您可以更改条件以使用它而不是True,或者(如果需要)使用break语句退出循环

作为旁注,使用忽略所有错误的try/except不是一个好主意;您应该只忽略您知道可以忽略的特定错误


确切的代码取决于message.GetNext()如何表示没有更多的消息,您可以在文档中查找,也可以尝试查看;但是,假设它返回None,代码如下所示:

message = messages.GetFirst()

while message is not None:
    print (message)
    # process the message, download the attachments etc

    message = messages.GetNext()

使用for循环代替while循环

for message in messages:
    try:
        attachments = message.Attachments
        attachment = attachments.Item(1)
        attachment.SaveASFile(os.getcwd() + '\\' + str(attachment)) #Saves to the attachment to current folder
        print(attachment)
        print(message)
    except:
        pass

相关问题 更多 >