This application demonstrates how you can work with a late bound object. The OLE server in this instance is Windows MAPI. Using MAPI in this way uses Outlook sort of through the back door; you don't actually create an instance of Outlook, but this sample demonstrates how closely tied MAPI and Outlook are. In fact, the mail side of Outlook isn't much more than a nice GUI to the Windows MAPI. If you are connected to an Exchange server when this simple application runs, the mail is sent automatically; otherwise, the mail is placed in Outlook's outbox, ready for you to send. You may also have to change the profile name to match that on your own system.
The sample function shown below is called from a form containing a text box (txtDomain) that holds the domain name of the recipients, and a list box (lstEmails) that holds the individual addresses of the recipients. This example is in fact part of a working application used several times a day to send test messages to new email accounts:
Private Function SendReturnEMail() As Boolean
' create an error handler On Error GoTo SendReturnEMail_Err
'set the default return value SendReturnEMail = False
'we're using late binding for this app Dim objSession As Object Dim objMessage As Object
86 Chapter 5 - Automation
Dim objRecipient As Object
'declare some other utility variables
Dim sSubject Dim sText Dim sName
As Integer As String As String As String
'set up the email message text sText = "This is an automatic test message, " & _ vbCrLf & _
"Please reply to the sender confirming receipt. 'and the subject sSubject = "Test Message"
'start with the top of the mapi hierarchy -'the session object
Set objSession = CreateObject("mapi.session") 'use the local Outlook default profile objSession.LogOn profilename:="Microsoft Outlook"
'this application will send a number of test messages 'to the members of a particular domain For i = 0 To lstEmails.ListCount - 1
'build the addresses from the names in the list
'and the given domain name sName = Trim(lstEmails.List(i)) & & _
Trim(txtDomain.Text) 'now create a new message object Set objMessage = objSession.outbox.messages.Add 'feed in the required property values for the 'message objMessage.subject = sSubject objMessage.Text = sText
'create a new recipient for this message Set objRecipient = objMessage.Recipients.Add 'and set it's properties objRecipient.Name = sName objRecipient.Type = 1
'make sure the email address is resolved objRecipient.resolve 'now send the message objMessage.Send showdialog:=False 'tidy up this message Set objRecipient = Nothing Set objMessage = Nothing 'and go round again for the next one Next i
'all done so off we go objSession.logoff 'tidying up as always Set objSession = Nothing 'set the success return value SendReturnEMail = True
Automation Examples 87
MsgBox Err.Number & vbCrLf & Err.Description & vbCrLf _ & Err.Source
Was this article helpful?