[英]Python: Move all outlook emails to different folder
我正在從事一個項目,該項目涉及從收到的電子郵件中抓取數據。
我堅持的部分是,在將郵件帶入本地內存后,我正在嘗試將電子郵件從原始位置移動到存檔文件夾,因為此過程將每周運行一次,我想確保事情不會發生被重復計算。
我正在使用一種非常標准的方法將電子郵件加載到內存中,但需要注意的是電子郵件將進入一個單獨的電子郵件組,而不是我的本地電子郵件帳戶,這增加了一個步驟。 它看起來像這樣:
outlook = win32com.client.Dispatch('Outlook.Application').GetNamespace('MAPI')
folder =outlook.Folders.Item('Product Alerts')
tempBox = folder.Folders.Item('Inbox')
inbox = tempBox.Folders.Item('Electronic Product Alert')
archiveFolder = folder.Folders.Item('Product Alert Archive')
messages = inbox.Items
#this is the part that isn't working
for email in inbox.Items:
email.Move(archiveFolder)
問題在於將電子郵件移動到存檔文件夾的循環不會移動文件夾中的所有電子郵件,它會移動一些並留下其他的。
我也試過
for message in messages:
message.Move(archiveFolder)
它和 inbox.Items 做同樣的事情
我還檢查以確保郵件正確加載,以確保與 Outlook 通信沒有問題,但正在運行
print(len(messages))
給出文件夾中電子郵件數量的正確結果。
我是否遺漏了一些明顯的東西來阻止這個循環將所有電子郵件移動到存檔文件夾,或者我是否需要使用不同的方法?
您的代碼在循環其元素時正在修改集合(通過調用Move
)。
使用messages.Count
中的向下循環。倒數到 1。
首先,我建議使用GetDefaultFolder方法來獲取收件箱文件夾,然后才處理子文件夾。
tempBox = folder.Folders.Item('Inbox')
可以替換此調用,因為根據用戶的語言環境,名稱可能會有所不同。
在下面的代碼中,您沒有考慮到項目被移動並且集合被減少,所以每次減少一個項目:
#this is the part that isn't working
for email in inbox.Items:
email.Move(archiveFolder)
相反,您需要在代碼中使用反向 for 循環來移動或刪除集合中的項目:
For i = Items.Count To 1 Step -1
Items(i).Move(..)
Next
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.