问题
I would like to write a script, that sends an E-Mail via our companys SMTP-Server using CDO.
First I tried to write an HTA-application for that purpose, but it became rather fiddly to make it cormfortable enough so that other people may handle it well (because of proper recipient resolving).
So now I try to use the regular Outlook-Mail mask to prepare the mail first and then catch the send-item event via VBScript to give it's content to my CDO script.
Right now, my code looks like this:
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
The main problem is, that Cancel = True simply does not work. Outlook will send my mail using my regular mail adress no matter what. Can you tell me, what I'm doing wrong please?
Thank you very much in advance!
Guido
回答1:
The Cancel parameter must be declared with the ByRef
modifier.
回答2:
Updated code as requested: Dim OutlookApplication Dim MailItem Dim CDODone: CDODone = False Const olDiscard = 1 Const olMailItem = 0
Set OutlookApplication = WScript.CreateObject("Outlook.Application", "Outlook_")
Set MailItem = OutlookApplication.CreateItem(olMailItem)
MailItem.UserProperties.Add "CDOFlag", 20, false, false
MailItem.Display
'(...) some code to add recipients, subject, text, etc... depending on the given WScript.Arguments
While Not CDODone Is Nothing
'keep the script alive
WScript.Sleep 1
WEnd
MailItem.Close olDiscard
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, byRef Cancel)
If Not Item.UserProperties.Find(CDOFlag) Is Nothing Then
Cancel = True
If CDOSendMessage() then
CDODOne = True
Else
Cancel = False
MsgBox "Sending message via CDO failed."
WScript.Quit
End If
End If
End Sub
来源:https://stackoverflow.com/questions/54146978/handling-com-event-cancelation-in-vbscript