首页 > 解决方案 > 在 VBScript 中处理 COM 事件取消

问题描述

我想编写一个脚本,使用 CDO 通过我们公司的 SMTP 服务器发送一封电子邮件。

首先,我尝试为此目的编写一个 HTA 应用程序,但是让它变得足够舒适以便其他人可以很好地处理它变得相当繁琐(因为正确的接收者解析)。

所以现在我尝试使用常规的 Outlook-Mail 掩码首先准备邮件,然后通过 VBScript 捕获 send-item 事件以将其内容提供给我的 CDO 脚本。

现在,我的代码如下所示:

Dim OutlookApplication
Dim MailItem
Const olDiscard = 1
Const olMailItem = 0

Set OutlookApplication = WScript.CreateObject("Outlook.Application", "Outlook_")
Set MailItem = OutlookApplication.CreateItem(olMailItem)
MailItem.Display

'(...) some code to add recipients, subject, text, etc... depending on the given WScript.Arguments

While Not MailItem Is Nothing
    'keep the script alive
    WScript.Sleep 1
WEnd

Function CDOSendMessage()
    'some code to send the data to our smtp server, return true if successfull
    CDOSendMessage = True
End Function

Sub Outlook_ItemSend(byVal Item, Cancel)
    If Item.body = MailItem.body Then 'Any more fail proof suggestions on how to check if it's the correct mailitem I'm handling with this event? While the script is alive, it fires for EVERY mail I send via outlook
        Cancel = True

        If CDOSendMessage() then
            Set MailItem = Nothing
            MailItem.Close olDiscard
        Else
            Cancel = False
            MsgBox "Sending message via CDO failed."
        End If
    End If
End Sub

主要问题是 Cancel = True 根本不起作用。无论如何,Outlook 都会使用我的常规邮件地址发送我的邮件。你能告诉我,我做错了什么吗?

非常感谢您!

圭多

标签: eventsoutlookvbscriptwshcdo.message

解决方案


必须使用ByRef修饰符声明 Cancel 参数。


推荐阅读