[英]stop while loop after downloading email attachments - 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()
使用 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
只要條件保持為真,while 循環就會永遠運行下去。 只需增加循環以確保它在最后變為假。 例如,您可以在 while 循環上方設置一個變量 status 並將其設置為 true..... while 循環的條件可以是 while status == 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.