[英]Sync all folders outlook win32 Python
我想等到 Outlook 中的所有文件夾都同步后才能開始下載附件。 如果我在沒有打開 Outlook 和同步所有文件夾的情況下運行代碼,則代碼不會下載最新的電子郵件。
代碼如下:
import os
import win32com
class DailyExtracts:
def __init__(self):
self.outlook = win32com.client.Dispatch("outlook.application").GetNamespace("MAPI")
self.root = self.outlook.Folders.item(1)
self.daily_reports = self.root.Folders[".data"].Folders["daily_reports"]
def download_extracts(self):
for message in self.daily_reports.Items:
for attachment in message.Attachments:
fname = attachment.Filename
attachment.SaveAsFile(os.path.join(os.path.expanduser(r"~\Downloads"), fname))
message.Unread = False
我已經讀到我可以使用 SyncObjects.SyncEnd 事件來等待發送/接收完成。 但是,我不知道如何實現它。
這是一個(可能不雅的)解決方案,它顯示了處理 Outlook 事件的基本原則。 處理 COM 事件(例如由 Outlook 生成)的問題在於它們是異步的,並且代碼必須等待事件被觸發。 此代碼使用線程的消息循環進行阻塞,直到所有 Sync 事件都返回為止。
處理程序類所做的不僅僅是 OP 需要的,而且還響應同步錯誤。
import win32com.client as wc
import pythoncom
import win32api
import win32con
nSync = 0
#Class to handle the SyncObject events from Outlook
class SyncHandler(object):
#Save the dispatch interface to identify the SyncObject if needed
def set(self,disp):
self._disp = disp
def _process(self):
#Decrement sync counter
global nSync
nSync -= 1
print(nSync,'Sync remaining to complete')
#If nothing left to sync, then send WM_QUIT to thread message loop
if nSync <= 0:
print('Closing message loop')
win32api.PostThreadMessage(win32api.GetCurrentThreadId(), win32con.WM_QUIT, 0, 0)
def OnSyncStart(self):
print('Starting sync on',self._disp.Name)
def OnSyncEnd(self):
print('Sync complete on',self._disp.Name)
self._process()
def OnProgress(self,state,description,value,max):
print('Sync progress: {0:} {1:} {2:}%'.format(self._disp.Name,description,100 * value/max))
def OnError(self,code,description):
print('Sync Error',description)
self._process()
#Get the application Dispatch interface
ol = wc.Dispatch('Outlook.Application')
syncObjects = ol.GetNamespace('MAPI').SyncObjects
#Find out how many SyncObjects we have
nSync = syncObjects.Count
print('Number of Sync objects:',nSync)
for syncObj in syncObjects:
#Set up an event handler and specify the event handler class
handler = wc.WithEvents(syncObj,SyncHandler)
handler.set(syncObj)
syncObj.Start()
#This will block until a WM_QUIT message is sent to the message queue
pythoncom.PumpMessages()
我在我的 Outlook 客戶端上測試了這個,它有許多電子郵件帳戶,它似乎工作正常,但我覺得它只同步非 Exchange 帳戶(因為我猜 Exchange 帳戶是持續同步的?)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.