簡體   English   中英

打開電子郵件時會觸發 Python Outlook win32 事件

[英]Python Outlook win32 event trigger when email is opened

我的目標是每當我在 Outlook 上打開電子郵件時,使用 python 腳本觸發事件處理程序,從那里我應該能夠獲取打開的電子郵件的數據,然后對數據進行處理。 有一個關於如何通過 VBA 執行此操作的類似線程( 此處),但我不知道如何使用 win32com 將其轉換為 python。

我已經瀏覽了 microsoft 文檔,但無法弄清楚如何在 MailItem 對象上觸發事件。 https://docs.microsoft.com/en-us/office/vba/api/outlook.mailitem

我最接近做的事情是通過做類似下面的事情,這可能不是解決方案,因為在這種情況下(如文檔所述)不包含數據。

import win32com.client
import pythoncom
import re

class Handler_Class(object):
  def OnItemLoad(self, item):
       print(item.Class)
 
outlook = win32com.client.DispatchWithEvents("Outlook.Application",Handler_Class)

任何想法/建議表示贊賞! 提前致謝!

這里有一些對我有用的概念證明,來自 SO 帖子的混合,包括這個: How to pass arguments to win32com event handler 它打印出的Subject行和Body時的MailItem讀的。

OP 代碼的額外步驟是處理Application.ItemLoad事件,並使用傳遞的信息繼續為 Item 單獨設置處理程序。 此外,由於您的 MailItem 處理程序在事件處理程序調用中沒有收到thisself指針(即 MailItem 的 IDispatch 接口),您必須自己保存以備后用。

import win32com.client
import pythoncom

#Handler for Application Object
class Application_Handler(object):
    def OnItemLoad(self, item):
        print('Application::OnItemLoad')

        #Only want to work with MailItems 
        if( item.Class == win32com.client.constants.olMail ): 
            #Get a Dispatch interface to the item
            cli = win32com.client.Dispatch(item)
            #Set up a handler
            handler = win32com.client.WithEvents(cli,MailItem_Handler)
            #Store the MailItem's Dispatch interface for use later
            handler.setDisp(cli)
 
#Handler for MailItem object
class MailItem_Handler(object):
    def setDisp(self,disp):
        self._disp = disp

    def OnOpen(self,bCancel):
        print('MailItem::OnOpen')
    
    def OnRead(self):
        print('MailItem::OnRead')
        subj = self._disp.Subject
        print('Subject:',subj)
        body = self._disp.Body
        print('Body:',body)

outlook = win32com.client.DispatchWithEvents("Outlook.Application", Application_Handler)
#Message loop
pythoncom.PumpMessages()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM