Sending Mail

After the application has successfully established a MAPI session, it can send a message. Sending a text-only message is trivial. Sending attachments and rich text is somewhat harder and is discussed later in this chapter.

Example 6-1 shows code that logs on to MAPI, sends a simple text message, and logs back off.

Example 6-1. Sending a Text Message

Dim CdoSession As MAPI.Session
Dim CdoFolder As MAPI.Folder
Dim CdoMessages As MAPI.Messages
Dim CdoMessage As MAPI.Message
Dim CdoRecipients As MAPI.Recipients
Dim CdoRecipient As MAPI.Recipient

' Establish a MAPI session.
Set CdoSession = New MAPI.Session
CdoSession.Logon "MyProfile"

' We must have a folder in which to create the outgoing message.
Set CdoFolder = CdoSession.Outbox

' Get the folder's messages collection, so that we can create
' a new message in it.
Set CdoMessages = CdoFolder.Messages

' Create the new message.
Set CdoMessage = CdoMessages.Add

' Set the message content.
CdoMessage.Subject = "This is the message subject."
CdoMessage.Text = "This is the message text."

' Get the message's recipients collection, so that we can
' add a recipient to it.
Set CdoRecipients = CdoMessage.Recipients

' Add a recipient.
Set CdoRecipient = CdoRecipients.Add

' Select an address.
CdoRecipient.Name = "William Gates"
CdoRecipient.Resolve

' Send the message.
CdoMessage.Send

Assuming that a MAPI session has already been established, creating and sending a message involves these steps:

  1. Obtain a Folder object in which to create ...

Get CDO & MAPI Programming with Visual Basic: now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.