我已经获得了下面的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()
只要条件保持为真,while循环将永远继续运行。只需增加循环,以确保它在最后变为false。 例如,您可以在while循环上方设置变量状态并将其设置为true。。。。。 while循环的条件可以是whilestatus==true。 在循环结束时,将状态重新声明为==false
当
message.GetNext()
方法指示不再有消息时,您可以更改条件以使用它而不是True
,或者(如果需要)使用break
语句退出循环作为旁注,使用忽略所有错误的
try
/except
不是一个好主意;您应该只忽略您知道可以忽略的特定错误确切的代码取决于
message.GetNext()
如何表示没有更多的消息,您可以在文档中查找,也可以尝试查看;但是,假设它返回None
,代码如下所示:使用for循环代替while循环
相关问题 更多 >
编程相关推荐