Dragon Drop - A Visual Basic Software Consultancy

Word Tips

Automating Outlook To Send EMail

This example creates an Outlook object from Word (though this could be from any application which permits COM to be used) and then sends a mail with the message body being mostly derived from a bookmark.

Make sure that the References include your appropriate version of the Outlook object model.


Public Sub OutlookEMail()

  Dim oOutlook As Outlook.Application
  Dim oMAPI As Outlook.NameSpace
  Dim oFolder As Outlook.MAPIFolder
  Dim oMailItem As Outlook.MailItem
  Dim oRecipient As Outlook.Recipient


  On Error Resume Next

  ' Create an instance of an Outlook Application
  Set oOutlook = New Outlook.Application
  If Not oOutlook Is Nothing Then

    ' Get the MAPI NameSpace object
    Set oMAPI = oOutlook.Session
    If Not oMAPI Is Nothing Then

      ' Log in to the MAPI session
      oMAPI.Logon , , True, True

      ' Create a pointer to the Outbox folder
      Set oFolder = oMAPI.GetDefaultFolder(olFolderOutbox)
      If Not oFolder Is Nothing Then

        ' Create a new item in the Outbox folder
        Set oMailItem = oFolder.Items.Add(olMailItem)
        If Not oMailItem Is Nothing Then
          With oMailItem
            .Subject = "Test offline mail"
            .Body = "This is a test message containing the text" & _
               "within the bookmark, 'bmkTextForMailing', range:" & vbCrLf & _
                ActiveDocument.Bookmarks("bmkTextForMailing").Range.Text


            ' Create the recipients
            Set oRecipient = .Recipients.Add("malcolm.smith@dragondrop.com")
            oRecipient.Type = olTo

            Set oRecipient = .Recipients.Add("ukhorseracing@hotmail.com")
            oRecipient.Type = olCC

            .Send

            Set oRecipient = Nothing
            Set oMailItem = Nothing
          End With

        End If

        Set oFolder = Nothing
      End If    ' oFolder check

      oMAPI.Logoff
    End If
    Set oMAPI = Nothing

  End If
  Set oOutlook = Nothing

End Sub

Updates

If there are any suggestions for updates then please drop me a mail at malcolm.smith@dragondrop.com.