Creating and Sending a Message

Creating and sending a message is easy when you use the CDO Library.

    To create and send a message
  1. Establish a session with the MAPI system.
  2. Call the Messages collection's Add method to create a Message object.
  3. Supply values for the Message object's Subject, Text, and other properties.
  4. Call the Recipients collection's Add method for each recipient, or copy the Recipients property from an existing message to the new message.
  5. If necessary, set each Recipient object's Address, AddressEntry, and Name properties.
  6. Call each Recipient object's Resolve method to validate the address information.
  7. Call the Message object's Send method.

The following code fragment demonstrates each of these steps for a message sent to a single recipient:

' This also appears as the "QuickStart" example in "Overview" 
Function QuickStart() 
Dim objSession As Object  ' or Dim objSession As MAPI.Session 
Dim objMessage As Object  ' or Dim objMessage As Message 
Dim objOneRecip As Object ' or Dim objOneRecip As Recipient 
 
    On Error GoTo error_olemsg 
 
' create a session then log on, supplying username and password 
Set objSession = CreateObject("MAPI.Session") 
' change the parameters to valid values for your configuration 
objSession.Logon 'profileName:="Jane Doe", _ 
                 'profilePassword:="my_pword" 
 
' create a message and fill in its properties 
Set objMessage = objSession.Outbox.Messages.Add 
objMessage.Subject = "Sample Message" 
objMessage.Text = "This is some sample message text." 
 
' create the recipient 
Set objOneRecip = objMessage.Recipients.Add 
objOneRecip.Name = "John Doe" 
objOneRecip.Type = CdoTo 
objOneRecip.Resolve 
 
' send the message and log off 
objMessage.Update 
objMessage.Send showDialog:=False 
MsgBox "The message has been sent" 
objSession.Logoff 
Exit Function 
 
error_olemsg: 
MsgBox "Error " & Str(Err) & ": " & Error$(Err) 
Resume Next 
 
End Function 
 

Note When you edit an object other than the Message object, save your changes using the Update method before you clear or reuse the variable that refers to the object. If you do not use the Update method, your changes can be lost without warning.

After calling the Message object's Send method, you should not try to access the Message object again. The Send method invalidates the Message object.

See Also

Adding Attachments to a Message, Customizing a Folder or Message