The following example demonstrates how easy it is to add messaging to your applications when you use Microsoft® Visual Basic® or Visual Basic for Applications.
In this code fragment, we first create a Session object and log on. We then create a Message object and set its properties to indicate its subject and content. Next we create a Recipient object and call its Resolve method to obtain a full messaging address. We then call the Message object's Send method to transmit the message. Finally, we display a completion message and log off.
' This sample uses Visual Basic 3.0 error handling.
'
Function QuickStart()
Dim objSession As MAPI.Session ' use early binding for more efficient
Dim objMessage As Message ' code and type checking
Dim objOneRecip As Recipient
On Error GoTo error_olemsg
' create a session and log on -- username and password in profile
Set objSession = CreateObject("MAPI.Session")
' change the parameters to valid values for your configuration
objSession.Logon profileName:="Sender Name"
' create a message and fill in its properties
Set objMessage = objSession.Outbox.Messages.Add
objMessage.Subject = "Sample Message"
objMessage.Text = "This is sample message text."
' create the recipient
Set objOneRecip = objMessage.Recipients.Add
objOneRecip.Name = "Recipient Name"
objOneRecip.Type = CdoTo
objOneRecip.Resolve ' get MAPI to determine complete e-mail address
' send the message and log off
objMessage.Send showDialog:=False
MsgBox "The message has been sent"
objSession.Logoff
Exit Function
error_olemsg:
MsgBox "Error " & Str(Err) & ": " & Error$(Err)
Exit Function
End Function
The CDO Library invalidates the Message object after you call its Send method. This code fragment logs off to end the session after sending the message, but if you continued the MAPI session, you could avoid potential errors by setting the Message object to Nothing.