[英]Python - Outlook save emails not saving all
下面的代碼在我運行腳本時保存來自特定文件夾的電子郵件 - 但是如果文件夾中有 5 或 6 封電子郵件,我必須運行兩次才能將它們全部清除 - 似乎無法正常工作 - 這是 python 版本我正在使用我曾經使用過 VBA 版本,它發生的方式相同 - 所以我認為這是 outlook 導致問題或我的兩個版本的編碼錯誤
from win32com.client import Dispatch
from datetime import datetime
from zipfile import ZipFile
from os import remove, listdir, rename, rmdir
from uuid import uuid4
import webbrowser
OUTLOOK = Dispatch("Outlook.Application").GetNamespace("MAPI")
BUSINESS_OBJECTS = OUTLOOK.Folders.Item(2).Folders['Inbox'].Folders['4. Regional'].Folders['Business Objects']
DIR = "\\\\GB998K12FPS01\\HomeDir$\\user001\\Desktop\\Exports\\Outlook attachments"
count = 0
for email in BUSINESS_OBJECTS.Items:
timestamp = str(datetime.fromtimestamp(email.ReceivedTime.timestamp())).replace(":", "-")
for attachment in email.attachments:
filename = "{}\\{} {}".format(DIR, timestamp, attachment.FileName)
attachment.SaveAsFile(filename)
if attachment.FileName.split(".")[-1] == "zip":
TEMP_FOLDER = "{}\\{}\\".format(DIR, uuid4())
with ZipFile(filename, "r") as zipped:
zipped.extractall(TEMP_FOLDER)
for file in listdir(TEMP_FOLDER):
rename(TEMP_FOLDER + file, "{}\\..\\{} {}".format(TEMP_FOLDER, timestamp, file))
remove(filename)
rmdir(TEMP_FOLDER)
if len(email.attachments) > 0:
email.UnRead = False
email.delete()
count += 1
print("Complete! Processed {} emails!".format(count))
input()
webbrowser.open("\\\\GB998K12FPS01\\HomeDir$\\user001\\Desktop\\Exports\\Outlook attachments"
any ideas would be greatly apprciated
考慮以下可能的情況:
Outlook 文件夾可能包含不同類型的項目,因此集合可能包含郵件項目、文檔項目、約會項目等。所以,我建議在進一步處理之前檢查項目類型。
遍歷文件夾中的所有項目並不是一個好主意:
for email in BUSINESS_OBJECTS.Items
相反,您可以考慮使用Items
class 的Find
/ FindNext
或Restrict
方法,這些方法只允許獲取與您的條件相對應的項目。 在以下文章中閱讀有關這些方法的更多信息:
DIR = "\\\\GB998K12FPS01\\HomeDir$\\user001\\Desktop\\Exports\\Outlook attachments"
...
filename = "{}\\{} {}".format(DIR, timestamp, attachment.FileName)
attachment.SaveAsFile(filename)
使用本地文件夾來保存附件。
無論如何,要了解為什么不是所有項目都被處理並將附加文件保存到磁盤,我建議在代碼中添加任何日志語句,這樣您就可以查看日志並了解代碼失敗的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.