我在 stackoverflow 上找到了以下代码,链接如下:打开电子邮件时Python Outlook win32事件触发
我正在尝试使用此代码并添加“def OnForward(self, disp, item):”以在我转发的电子邮件上添加签名。但前锋的表现并不好。我会尝试解释一下,每次我单击“转发”时,它都会在新窗口上弹出电子邮件,但也会出现在 Outlook 主窗口上,然后“def OnRead(self):”也停止工作!我不知道是否正确表达自己,但任何帮助将不胜感激
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,item):
print('MailItem::OnOpen')
def OnRead(self):
print('MailItem::OnRead')
subj = self._disp.Subject
print('Subject:',subj)
body = self._disp.Body
print('Body:',body)
def OnClose(self, item):
return
print('---------------MailItem::OnClose-------------------')
print('-----------------------------------------------------')
def OnForward(self, disp, item):
print('---------------MailItem::OnForward-------------------')
newMail = self._disp.Forward()
newMail.HTMLBody = self._disp.HTMLBody + 'teste'
newMail.Display()
print('-----------------------------------------------------')
outlook = win32com.client.DispatchWithEvents("Outlook.Application", Application_Handler)
#Message loop
pythoncom.PumpMessages()
每次我单击“转发”时,它都会在新窗口中弹出电子邮件,但也会出现在 Outlook 主窗口中
在
Forward
事件处理程序中,您可以找到以下代码:
newMail = self._disp.Forward()
newMail.HTMLBody = self._disp.HTMLBody + 'teste'
newMail.Display()
当相应的事件被触发时,它会一次又一次地调用
Forward
。因此, Forward
方法会引发 Forward
事件。
当用户为某个项目选择“Forward”操作或为该项目调用“Forward”方法时,将触发“Forward”事件。因此,无需在事件处理程序中重新调用它。这是对 Forward
方法的反应。转发的新项目作为参数传递给事件处理程序。
def OnForward(self, disp, item):
print('---------------MailItem::OnForward-------------------')
newMail = item
newMail.HTMLBody = self._disp.HTMLBody + 'teste'
newMail.Display()
print('-----------------------------------------------------')
Forward()
的调用是不必要的,并且会重复 Outlook 正在采取的操作。也无需打电话
Display()
。然而,虽然事件的签名是正确的,因为它需要两个参数,但隐含类型是错误的。第一个参数(self
之后)是指向新项目的 Dispatch 指针,第二个参数是允许处理程序取消事件的标志。
应该是:def OnForward(self,newItem,bCancel):
newItem.HTMLBody = self._disp.HTMLBody + 'teste'
只要事件处理程序未将 bCancel 设置为 True,newItem 就会显示。直到用户单击“发送”按钮或调用 Send() 方法后,newItem 才会真正被发送。
MailItem 及其事件的参考位于
此处bCancel=True
没有效果,并且该项目始终显示。我的猜测是
win32com
没有正确处理 [in,out] 引用参数。