【发布时间】:2023-01-09 01:59:26
【问题描述】:
使用 python 模块 win32com 当新邮件到达 outlook 时是否可以触发某些操作
伪代码
while 1
if a mail arrives
do x
编辑:我不允许使用“运行脚本”规则
【问题讨论】:
标签: python python-3.x outlook win32com
使用 python 模块 win32com 当新邮件到达 outlook 时是否可以触发某些操作
伪代码
while 1
if a mail arrives
do x
编辑:我不允许使用“运行脚本”规则
【问题讨论】:
标签: python python-3.x outlook win32com
将DispatchWithEvents函数用于Outlook NewMailEx event
例子
import pythoncom
from win32com.client import DispatchWithEvents
# Event handler class for Outlook events
class OutlookEventHandler(object):
@staticmethod
def OnNewMailEx(EntryIDCollection):
for ID in EntryIDCollection.split(","):
item = Outlook.Session.GetItemFromID(ID)
# check item class, 43 = MailItem
if item.Class == 43:
print(" Subj: " + item.Subject)
if __name__ == "__main__":
Outlook = DispatchWithEvents("Outlook.Application", OutlookEventHandler)
olNs = Outlook.GetNamespace("MAPI")
Inbox = olNs.GetDefaultFolder(6)
pythoncom.PumpMessages()
例子
import pythoncom
from win32com.client import DispatchWithEvents, Dispatch
# Event handler class for outlook events
class OutlookEvent(object):
@staticmethod
def OnItemAdd(item):
""" Name Required/Optional Data type Description
Item Required Object The item that was added."""
print(f'The item that was added = {item.Subject}')
if __name__ == "__main__":
outlook = Dispatch("outlook.Application")
olNs = outlook.GetNamespace("MAPI")
inbox = olNs.GetDefaultFolder(6)
event = DispatchWithEvents(inbox.Items, OutlookEvent)
pythoncom.PumpMessages()
【讨论】:
win32com.gencache.EnsureDispatch() 然后使用 WithEvents() 作为单独的调用。这将导致 gen_py 创建常量,因此您可以编写 win32com.client.constants.olMail 而不是 43。然后还需要通过这种方法使用 CastTo(IMailItem) 转换 item。副作用是它还对方法/属性强制区分大小写,这可以防止意外行为。
您可以创建运行 VBA 脚本的规则。该脚本可以执行您希望它执行的任何操作,包括运行您的 Python 代码。
【讨论】:
Application.NewMailEx 事件。