Eugene Astafiev

How To: Create and send an Outlook message programmatically

Today I want to tell you the story about sending messages in Outlook programmatically. In one of my recent posts I showed two possible ways of creating and showing a new Outlook message. And now I want to make an addition to that: demonstrate how you can send a message programmatically. So, let’s start!

The Outlook Object Model has the Send method. The MailItem, AppointmentItem, MeetingItem, MobileItem, SharingItem and TaskItem classes provide this method to the programmer. It doesn’t accept or return any value (or object). It just does its job – sends a message. However, in order to send a message Outlook needs to know whom to deliver it to. The Recipients property is used for such a task. It returns an instance of the Recipients class. The Recipients class contains all recipients of your message, i.e. instances of the Recipient class in Outlook.

The Recipients collection provides you the Add method that adds new recipients to the collection. The method accepts a string which contains the name of a recipient or a full SMTP e-mail address and returns a new instance of the Recipient class. Please pay special attention to the fact that the recipient’s name must be valid: it should have a corresponding entry in your address book .The collection also provides you the ResolveAll method, which doesn’t accept any parameters and returns a Boolean value indicating whether all recipients in the collection were resolved or not (false – if one or more entries were not resolved, i.e. don’t have corresponding entries in the address book). The Recipient class also provides the Resolved property which can be used instead of the ResolveAll method of the Recipients class. Note, if you specified an SMTP e-mail address, you don’t need to have a “mapped” entry in the address book – one-off entry will be created.

In the code below, I create a new mail object, set the Subject property in order to identify it in my Inbox and then add the recipient to the Recipients collection of the item. Then I check whether the recipient was resolved or not and, finally, send the message. Please note that you will need to replace the recipient’s name with a valid one from your Outlook address book to get the code running correctly. The CreateSendItem method accepts an instance of the Application class in Outlook and then does its job!

C# and Add-in Express:

private void CreateSendItem(Outlook._Application OutlookApp)
{
    Outlook.MailItem mail = null;
    Outlook.Recipients mailRecipients = null;
    Outlook.Recipient mailRecipient = null;
    try
    {
        mail = OutlookApp.CreateItem(Outlook.OlItemType.olMailItem)
           as Outlook.MailItem;
        mail.Subject = "A programatically generated e-mail";
        mailRecipients = mail.Recipients;
        mailRecipient = mailRecipients.Add("Eugene Astafiev");
        mailRecipient.Resolve();
        if (mailRecipient.Resolved)
        {
            mail.Send();
        }
        else
        {
            System.Windows.Forms.MessageBox.Show(
                "There is no such record in your address book.");
        }
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message,
            "An exception is occured in the code of add-in.");
    }
    finally
    {
        if (mailRecipient != null) Marshal.ReleaseComObject(mailRecipient);
        if (mailRecipients != null) Marshal.ReleaseComObject(mailRecipients);
        if (mail != null) Marshal.ReleaseComObject(mail);
    }
}

VB.NET and Add-in Express:

Private Sub CreateSendItem(OutlookApp As Outlook._Application)
    Dim mail As Outlook.MailItem = Nothing
    Dim mailRecipients As Outlook.Recipients = Nothing
    Dim mailRecipient As Outlook.Recipient = Nothing
    Try
        mail = OutlookApp.CreateItem(Outlook.OlItemType.olMailItem)
        mail.Subject = "A programatically generated e-mail"
        mailRecipients = mail.Recipients
        mailRecipient = mailRecipients.Add("Eugene Astafiev")
        mailRecipient.Resolve()
        If (mailRecipient.Resolved) Then
            mail.Send()
        Else
            System.Windows.Forms.MessageBox.Show(
                "There is no such record in your address book.")
        End If
    Catch ex As Exception
        System.Windows.Forms.MessageBox.Show(ex.Message,
            "An exception is occured in the code of add-in.")
    Finally
        If Not IsNothing(mailRecipient) Then Marshal.ReleaseComObject(mailRecipient)
        If Not IsNothing(mailRecipients) Then Marshal.ReleaseComObject(mailRecipients)
        If Not IsNothing(mail) Then Marshal.ReleaseComObject(mail)
    End Try
End Sub

C# and VSTO:

using System.Runtime.InteropServices;
// ...
private void CreateSendItem(Outlook.Application Application)
{
     Outlook.MailItem mail = null;
     Outlook.Recipients mailRecipients = null;
     Outlook.Recipient mailRecipient = null;
     try
     {
          mail = Application.CreateItem(Outlook.OlItemType.olMailItem)
              as Outlook.MailItem;
          mail.Subject = "A programatically generated e-mail";
          mailRecipients = mail.Recipients;
          mailRecipient = mailRecipients.Add("Eugene Astafiev");
          mailRecipient.Resolve();
          if (mailRecipient.Resolved)
          {
              mail.Send();
          }
          else
          {
              System.Windows.Forms.MessageBox.Show(
                  "There is no such record in your address book.");
          }
     }
     catch (Exception ex)
     {
         System.Windows.Forms.MessageBox.Show(ex.Message,
              "An exception is occured in the code of add-in.");
     }
     finally
     {
         if (mailRecipient != null) Marshal.ReleaseComObject(mailRecipient);
         if (mailRecipients != null) Marshal.ReleaseComObject(mailRecipients);
         if (mail != null) Marshal.ReleaseComObject(mail);
     }
}

VB.NET and VSTO:

Imports System.Runtime.InteropServices
' ...
Private Sub CreateSendItem(Application As Outlook.Application)
    Dim mail As Outlook.MailItem = Nothing
    Dim mailRecipients As Outlook.Recipients = Nothing
    Dim mailRecipient As Outlook.Recipient = Nothing
    Try
        mail = Application.CreateItem(Outlook.OlItemType.olMailItem)
        mail.Subject = "A programatically generated e-mail"
        mailRecipients = mail.Recipients
        mailRecipient = mailRecipients.Add("Eugene Astafiev")
        mailRecipient.Resolve()
        If (mailRecipient.Resolved) Then
            mail.Send()
        Else
            System.Windows.Forms.MessageBox.Show(
                "There is no such record in your address book.")
        End If
    Catch ex As Exception
        System.Windows.Forms.MessageBox.Show(ex.Message,
            "An exception is occured in the code of add-in.")
    Finally
        If Not IsNothing(mailRecipient) Then Marshal.ReleaseComObject(mailRecipient)
        If Not IsNothing(mailRecipients) Then Marshal.ReleaseComObject(mailRecipients)
        If Not IsNothing(mail) Then Marshal.ReleaseComObject(mail)
    End Try
End Sub

See you on our forums and in the e-mail support!

23 Comments

  • How do we do the above in MS 365 Outlook ?

  • Hi Brian,

    Please take a look at the Office 365 – Exchange Online examples article on our technical blog.

  • http://1.gravatar.com/avatar/fe5b6903b6ba6d5c1767ec1003369e9b?s=32&d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Candice says:

    I am a .net/c# developer. I am very new to Add-In-Express and VB. I am trying to send an email programatically from a button. I’ve copied the method for vb and Add-in-Express. How do i call CreateSendItem from the button click event, meaning what do i pass in?

  • Hello Candice,

    First of all, thank you for choosing Add-in Express!

    If you develop an Add-in Express based Outlook COM add-in, the AddinModule class provides you with the OutlookApp property which returns an instance of the Application class. You can pass that instance to the CreateSendItem method.

    If you have any questions or need further assistance don’t hesitate to contact our support team via our forums or e-mail.

  • http://1.gravatar.com/avatar/fe5b6903b6ba6d5c1767ec1003369e9b?s=32&d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Candice says:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles agencySubmit.Click
    CreateSendItem(OutlookApp)
    End Sub

    Gives me error.. “OutlookApp is not declared. It may be inaccessible due to its protection level”

    I did a search for OutlookApp and found it in AddinModule.vb

    Public ReadOnly Property OutlookApp() As Outlook._Application
    Get
    Return CType(HostApplication, Outlook._Application)
    End Get
    End Property

  • Candice,

    Where do you handle the Click event of the button?

    Anyway, please try to use the static AddinExpress.MSO.ADXAddinModule.CurrentInstance property to get an instance of the AddinModule class. Then you can cast it to your actual module type which provides the OutlookApp property.

  • http://1.gravatar.com/avatar/fe5b6903b6ba6d5c1767ec1003369e9b?s=32&d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Candice says:

    that helped me getting passed a successful build…

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles agencySubmit.Click
    CreateSendItem(AddinExpress.MSO.ADXAddinModule.CurrentInstance)
    End Sub

    but when i run it and click the button, it gives me a runtime error…
    “Unable to cast object of type ‘SalesOutlookAddin.AddinModule’ to type ‘Microsoft.Office.Interop.Outlook._Application’

  • Hi Candice,

    Note, you need to cast an instance of the AddinModule class to your actual module type which provides the OutlookApp property. Please try the following code:

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim app As Outlook.Application = CType(Me.AddinModule, MyAddin49.AddinModule).OutlookApp
    CreateSendItem(app)
    End Sub

  • http://0.gravatar.com/avatar/68ddec196852d1ad4092dec195e59e70?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Ebuka says:

    i tried this
    Dim app As Outlook.Application = CType(Me.AddinModule, MyAddin49.AddinModule).OutlookApp
    CreateSendItem(app)
    it gave me these errors 1.AddinModule is not a member of my form
    2.type “myaddin49.addmodule” is not defined
    is there a way to declare it

  • http://0.gravatar.com/avatar/ab4ec2858cfdf1e44dadf8c50fae314d?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Dmitry Kostochko (Add-in Express Team) says:

    Hi Ebuka,

    Where this code is being executed? Do you develop an Outlook add-in or a standalone application?

  • http://0.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?s=32 Ebuka says:

    I created a module in vb.net VSTO,and when I use the call createSendItem() how do I pass an argument to it

  • http://0.gravatar.com/avatar/ab4ec2858cfdf1e44dadf8c50fae314d?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Dmitry Kostochko (Add-in Express Team) says:

    Hi Ebuka,

    Thank you for the details. I think you can use the Globals.ThisAddIn.Application variable:
    CreateSendItem(Globals.ThisAddIn.Application)

  • http://0.gravatar.com/avatar/68ddec196852d1ad4092dec195e59e70?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Ebuka says:

    i hav this code to call my module:
    Globals.ThisAddIn.Application.CreateSendItem()
    CreateSendItem(Globals.ThisAddIn.Application)
    i assume variable is the name of my module
    but i get a line under global telling me that name ‘globals’ is not declared

  • http://0.gravatar.com/avatar/ab4ec2858cfdf1e44dadf8c50fae314d?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Dmitry Kostochko (Add-in Express Team) says:

    Hi Ebuka,

    When you create a VSTO project, Visual Studio automatically generates a class named Globals in the project. So, you should have access to the Globals class. Could you please send me your project for testing?

  • http://0.gravatar.com/avatar/68ddec196852d1ad4092dec195e59e70?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Ebuka says:

    i created an infopath form,and will add the values of the fields to an excel work sheet the code below does that in vb.net:
    N:B reference the COM microsoft excel 14.0 object and microsoft outlook 14.0 object for the module im using VSTO vb.net 2010

    Imports Microsoft.Office.InfoPath
    Imports System
    Imports System.Xml
    Imports excel = Microsoft.Office.Interop.Excel
    Imports office = Microsoft.Office.core
    Imports Outlook = Microsoft.Office.interop.Outlook
    Imports Microsoft.Office.Interop.Outlook
    Imports System.Windows.forms
    Imports System.Xml.XPath

    Namespace newblank
    Public Class FormCode
    ‘ Member variables are not supported in browser-enabled forms.
    ‘ Instead, write and read these values from the FormState
    ‘ dictionary using code such as the following:

    ‘ Private Property _memberVariable() As Object
    ‘ Get
    ‘ _memberVariable = FormState(“_memberVariable”)
    ‘ End Get
    ‘ Set
    ‘ FormState(“_memberVariable”) = value
    ‘ End Set
    ‘ End Property

    ‘ NOTE: The following procedure is required by Microsoft InfoPath.
    ‘ It can be modified using Microsoft InfoPath.
    Private Sub InternalStartup(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Startup
    AddHandler DirectCast(EventManager.ControlEvents(“CTRL4_5″), ButtonEvent).Clicked, AddressOf CTRL4_5_Clicked

    End Sub

    Public Sub CTRL4_5_Clicked(ByVal sender As Object, ByVal e As ClickedEventArgs)
    ‘ Write your code here.
    Dim xlApp As New excel.Application
    Dim xlWb As excel.Workbook
    Dim xlsheet As excel.Worksheet
    Dim rs As excel.Range
    Dim lRow As Long = 0
    With xlApp
    .Visible = True

    xlWb = .Workbooks.Open(“\\NIGLAGFN001\einwach$\Sync\ebuka.xlsx”)

    xlsheet = xlWb.Sheets(“Sheet1″)
    With xlsheet

    If xlApp.WorksheetFunction.CountA(.Cells) 0 Then
    lRow = .Cells.Find(What:=”*”, _
    After:=.Range(“A1″), _
    LookAt:=excel.XlLookAt.xlPart, _
    LookIn:=excel.XlFindLookIn.xlFormulas, _
    SearchOrder:=excel.XlSearchOrder.xlByRows, _
    SearchDirection:=excel.XlSearchDirection.xlPrevious, _
    MatchCase:=False).Row + 1
    Else
    lRow = 1
    End If
    End With
    Dim fieldValue As String = MainDataSource.CreateNavigator().SelectSingleNode( _
    “/my:myFields/my:field1″, NamespaceManager).Value
    Dim fieldValue1 As String = MainDataSource.CreateNavigator().SelectSingleNode( _
    “/my:myFields/my:field2″, NamespaceManager).Value
    With xlsheet

    .Range(“A” & lRow).Value = fieldValue
    .Range(“B” & lRow).Value = fieldValue1
    System.Windows.Forms.MessageBox.Show(“inputed”)
    Dim lblUserName As String
    lblUserName = SystemInformation.UserName
    System.Windows.Forms.MessageBox.Show(lblUserName)
    End With

    call createSendItem()’the module is called here

    End With

    releaseObject(xlsheet)
    releaseObject(xlWb)
    releaseObject(xlApp)

    End Sub

    Private Sub releaseObject(ByVal obj As Object)
    Try
    System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
    obj = Nothing
    Catch ex As System.Exception
    obj = Nothing
    Finally
    GC.Collect()
    End Try
    End Sub

    End Class
    End Namespace

    then a module to send mail when the excel worksheet has been updated
    Imports Outlook = Microsoft.Office.interop.Outlook
    Imports Microsoft.Office.Interop.Outlook
    Imports System.Net.Mail
    Imports System.Windows.forms
    Imports System.Runtime.InteropServices
    Module Module1
    Public Sub CreateSendItem(ByVal Application As Outlook.Application)

    Dim mail As Outlook.MailItem = Nothing
    Dim mailRecipients As Outlook.Recipients = Nothing
    Dim mailRecipient As Outlook.Recipient = Nothing
    Try
    mail = Application.CreateItem(Outlook.OlItemType.olMailItem)
    mail.Subject = “A programatically generated e-mail”
    mailRecipients = mail.Recipients
    mailRecipient = mailRecipients.Add(“aliyu ishaku”)
    mailRecipient.Resolve()
    If (mailRecipient.Resolved) Then
    mail.Send()
    Else
    System.Windows.Forms.MessageBox.Show(“There is no such record in your address book.”)
    End If
    Catch ex As System.Exception
    System.Windows.Forms.MessageBox.Show(ex.Message, “An exception is occured in the code of add-in.”)
    Finally
    If Not mailRecipient Is Nothing Then Marshal.ReleaseComObject(mailRecipient)
    If Not mailRecipients Is Nothing Then Marshal.ReleaseComObject(mailRecipients)
    If Not mail Is Nothing Then Marshal.ReleaseComObject(mail)
    End Try

    End Sub

    End Module
    then the it gives me the error name ‘globals’ is not declared

  • http://0.gravatar.com/avatar/ab4ec2858cfdf1e44dadf8c50fae314d?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Dmitry Kostochko (Add-in Express Team) says:

    Hi Ebuka,

    You can try this code:

    Dim olApp As New Outlook.Application
    Dim ns As Outlook._NameSpace = olApp.GetNamespace(“MAPI”)
    ns.Logon()
    CreateSendItem(olApp)
    Marshal.ReleaseComObject(ns)
    Marshal.ReleaseComObject(olApp)

  • http://0.gravatar.com/avatar/68ddec196852d1ad4092dec195e59e70?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Ebuka says:

    Thanks, i had a successful build but a run time error that “An exception is occured in the code of add-in”
    wud appreciate ur help

  • http://0.gravatar.com/avatar/ab4ec2858cfdf1e44dadf8c50fae314d?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Dmitry Kostochko (Add-in Express Team) says:

    Ebuka,

    Please debug your code. What code line throws the exception?

  • http://0.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?s=32 Ebuka says:

    This is the line Catch ex As System.Exception
    System.Windows.Forms.MessageBox.Show
    (ex.Message, “An exception is occured in the code of
    add-in.”)

  • http://0.gravatar.com/avatar/68ddec196852d1ad4092dec195e59e70?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Ebuka says:

    keeps giving me the error:operations aborted(exception from HRESULT:00×80004004 (E_ABORT)

  • http://0.gravatar.com/avatar/ab4ec2858cfdf1e44dadf8c50fae314d?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Dmitry Kostochko (Add-in Express Team) says:

    Hi Ebuka,

    That provides me with no information at all to provide help. I need to know which exactly code line throws the exception. Is it possible for you to send me the whole project (or some demo project with the same behavior) for testing?

  • http://0.gravatar.com/avatar/21b0f1406aabd62c696360b085b85108?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G Mauro Santos says:

    Hi Eugene,
    What the best away to save email as msg in send event?
    I’ve no problems to save it to temp file, but when i open the file (*.msg) the email is in unsent state. Add-in express have any event before send event?

  • Hello Mauro,

    The email isn’t sent yet when in the ItemSend event. And if you intercept the MailItem.Send event, the it occurs even before the ItemSend event.

    The email has MailItem.Sent set to true when its copy is saved to the Sent Items folder (or to the folder specified in the MailItem.SaveSentMessageFolder property). Try intercepting the ItemAdd event of the Items collection of that folder and use MailItem.SavesAs. In Add-in Express the ItemAdd event is mapped to the ProcessItemAdd method of the Outlook Items (not Item!) Events class, see the Add New Item dialog of your add-in project.

Post a comment

Have any questions? Ask us right now!