Eugene Astafiev

How to create and show a new Outlook mail item programmatically: C#, VB.NET

One of the most widespread tasks in Outlook is creating and showing an email messahe (mail item) to the user programmatically, or just sending it silently. Today I will teach you how to do it in two different manners using either C# or VB.NET. So, let’s move on and start digging!

The fist and the simplest way is to use the CreateItem method of the Application class in Outlook. This method accepts the OlItemType enumeration and returns a newly created item.

Another way to create a new Outlook mail item is to use the Add method of the Items class in Outlook. As you may probably know, each Outlook Folder provides you the Items property. This property returns an instance of the Items class, it is the class that we are mostly interested in. The Add method expects to receive either the OlItemType enumeration or a string representing a message class when you create custom items. The parameter is optional. If you decide to omit it, a MailItem object will be created.

The difference between the two ways of creating Outlook mail items is that the first one (the CreateItem method) doesn't allow creating custom items based on the specified message class. Also I want to draw your attention to the fact that Outlook items are always created and saved to the Drafts folder regardless whether you use the Items property of the Drafts folder or some other folder. Say, you used the Items property of the Inbox folder to create an Outlook item. You may expect to see the newly created item in the Inbox folder right after you call the Save method. But it will be listed in the Drafts folder anyway! In that case you need to move it to the Inbox folder and save it there. Please see the CreateShowMessageUsingItemsAdd method where I implemented the described scenario.

To show somehting in Outlook to the user, like a folder, Explorer window, Inspector window or just an item, you need to use the Display method. This method accepts a Boolean value indicating whether to show an item in a modal or non-modal window. You need to pass true if you want to show an item in the modal window.

Below you can find the code that creates Outlook items in the two ways I have just outlined. For demonstration purposes I create a MailItem object and then show it to the user. To get the code running, you merely need to pass an instance of the Application class to the CreateShowMessageUsingCreateItem and CreateShowMessageUsingItemsAdd methods.

C# and Add-in Express (create a new Mail item using CreateItem method):

private void CreateShowMessageUsingCreateItem(Outlook._Application OutlookApp)
{
    Outlook.MailItem mail = null;
    try
    {
        mail = OutlookApp.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;        
        mail.Save();
        mail.Display(false);
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message);
    }
    finally
    {
        if (mail != null) Marshal.ReleaseComObject(mail);
    }
}

C# and Add-in Express (create a new Mail item using Add method):

private void CreateShowMessageUsingItemsAdd(Outlook._Application OutlookApp)
{
     Outlook.NameSpace nSpace = null;
     Outlook.MAPIFolder targetFolder = null;
     Outlook.Items folderItems = null;
     Outlook.MailItem mail = null;
     Outlook.MailItem movedMail = null;
     try
     {
         nSpace = OutlookApp.GetNamespace("MAPI");
         targetFolder = nSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
         folderItems = targetFolder.Items;
         mail = folderItems.Add(Outlook.OlItemType.olMailItem) as Outlook.MailItem;                        
         // move the item to Inbox and then save it there
         movedMail = mail.Move(targetFolder) as Outlook.MailItem;
         movedMail.Save();
         movedMail.Display(false); 
     }
     catch (Exception ex)
     {
         System.Windows.Forms.MessageBox.Show(ex.Message);
     }
     finally
     {
         if (movedMail != null) Marshal.ReleaseComObject(movedMail);
         if (mail != null) Marshal.ReleaseComObject(mail);
         if (folderItems != null) Marshal.ReleaseComObject(folderItems);
         if (targetFolder != null) Marshal.ReleaseComObject(targetFolder);
         if (nSpace != null) Marshal.ReleaseComObject(nSpace);
     }
}

VB.NET and Add-in Express (using CreateItem method):

Private Sub CreateShowMessageUsingCreateItem(OutlookApp As Outlook._Application)
    Dim mail As Outlook.MailItem = Nothing
    Try
        mail = OutlookApp.CreateItem(Outlook.OlItemType.olMailItem)        
        mail.Save()
        mail.Display(True)
    Catch ex As Exception
        System.Windows.Forms.MessageBox.Show(ex.Message)
    Finally
        If Not IsNothing(mail) Then
            Marshal.ReleaseComObject(mail)
        End If
    End Try
End Sub

VB.NET and Add-in Express (using Add method):

Private Sub CreateShowMessageUsingItemsAdd(OutlookApp As Outlook._Application)
    Dim nSpace As Outlook.NameSpace = Nothing
    Dim targetFolder As Outlook.MAPIFolder = Nothing
    Dim folderItems As Outlook.Items = Nothing
    Dim mail As Outlook.MailItem = Nothing
    Dim movedMail As Outlook.MailItem = Nothing
    Try
        nSpace = OutlookApp.GetNamespace("MAPI")
        targetFolder = nSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
        folderItems = targetFolder.Items
        mail = folderItems.Add(Outlook.OlItemType.olMailItem)
        ' move the item to Inbox and then save it there 
        movedMail = mail.Move(targetFolder)
        movedMail.Save()
        movedMail.Display(False)
    Catch ex As Exception
        System.Windows.Forms.MessageBox.Show(ex.Message)
    Finally
        If Not IsNothing(movedMail) Then Marshal.ReleaseComObject(movedMail)
        If Not IsNothing(mail) Then Marshal.ReleaseComObject(mail)
        If Not IsNothing(folderItems) Then Marshal.ReleaseComObject(folderItems)
        If Not IsNothing(targetFolder) Then Marshal.ReleaseComObject(targetFolder)
        If Not IsNothing(nSpace) Then Marshal.ReleaseComObject(nSpace)
    End Try
End Sub

C# and VSTO (using CreateItem method):

using System.Runtime.InteropServices;
// ...
private void CreateShowMessageUsingCreateItem(Outlook.Application Application)
{
    Outlook.MailItem mail = null;
    try
    {
        mail = Application.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
        mail.Save();
        mail.Display(false);
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message);
    }
    finally
    {
        if (mail != null) Marshal.ReleaseComObject(mail);
    }
}

C# and VSTO (using Add method):

using System.Runtime.InteropServices;
// ...
private void CreateShowMessageUsingItemsAdd(Outlook.Application Application)
{
    Outlook.NameSpace nSpace = null;
    Outlook.MAPIFolder targetFolder = null;
    Outlook.Items folderItems = null;
    Outlook.MailItem mail = null;
    Outlook.MailItem movedMail = null;
    try
    {
        nSpace = Application.GetNamespace("MAPI");
        targetFolder = nSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
        folderItems = targetFolder.Items;
        mail = folderItems.Add(Outlook.OlItemType.olMailItem) as Outlook.MailItem;        
        // move the item to Inbox and then save it there
        movedMail = mail.Move(targetFolder) as Outlook.MailItem;
        movedMail.Save();
        movedMail.Display(false);
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message);
    }
    finally
    {
        if (movedMail != null) Marshal.ReleaseComObject(movedMail);
        if (mail != null) Marshal.ReleaseComObject(mail);
        if (folderItems != null) Marshal.ReleaseComObject(folderItems);
        if (targetFolder != null) Marshal.ReleaseComObject(targetFolder);
        if (nSpace != null) Marshal.ReleaseComObject(nSpace);
    }
}

VB.NET and VSTO (using CreateItem method):

Imports System.Runtime.InteropServices
'...
Private Sub CreateShowMessageUsingCreateItem(Application As Outlook.Application)
    Dim mail As Outlook.MailItem = Nothing
    Try
        mail = Application.CreateItem(Outlook.OlItemType.olMailItem)        
        mail.Save()
        mail.Display(False)
    Catch ex As Exception
        System.Windows.Forms.MessageBox.Show(ex.Message)
    Finally
        If Not IsNothing(mail) Then Marshal.ReleaseComObject(mail)
    End Try
End Sub

VB.NET and VSTO (using Add method):

Imports System.Runtime.InteropServices
'...
Private Sub CreateShowMessageUsingItemsAdd(Application As Outlook.Application)
    Dim nSpace As Outlook.NameSpace = Nothing
    Dim targetFolder As Outlook.MAPIFolder = Nothing
    Dim folderItems As Outlook.Items = Nothing
    Dim mail As Outlook.MailItem = Nothing
    Dim movedMail As Outlook.MailItem = Nothing
    Try
        nSpace = Application.GetNamespace("MAPI")
        targetFolder = nSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
        folderItems = targetFolder.Items
        mail = folderItems.Add(Outlook.OlItemType.olMailItem)        
        ' move the item to Inbox and then save it there
        movedMail = mail.Move(targetFolder)
        movedMail.Save()
        movedMail.Display(False)
    Catch ex As Exception
        System.Windows.Forms.MessageBox.Show(ex.Message)
    Finally
        If Not IsNothing(movedMail) Then Marshal.ReleaseComObject(movedMail)
        If Not IsNothing(mail) Then Marshal.ReleaseComObject(mail)
        If Not IsNothing(folderItems) Then Marshal.ReleaseComObject(folderItems)
        If Not IsNothing(targetFolder) Then Marshal.ReleaseComObject(targetFolder)
        If Not IsNothing(nSpace) Then Marshal.ReleaseComObject(nSpace)
    End Try
End Sub

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

29 Comments

  • Hameem says:

    Hi nice is to see your article about new Outlook message programmatically. i tried your code its worked fine. my requirment is programmatically pass the values to outlook and once a user click “send” button in the outlook ,what ever the data user update in the outlook should able to receive in the program. i tried display(true) but once we send the mail object is clear so i cannot receive any data. can you please give me a solution in this.

  • Eugene Astafiev says:

    Hi Hameem,

    You can call public methods and properties of your add-in module using the COMAddins property of the host application. Please take a look at the “HowTo: Communicate with a COM add-in from a standalone application” article on our technical blog at https://www.add-in-express.com/creating-addins-blog/standalone-application-addin-communicate/ for more information on this.

  • Trevor Yearwood says:

    Great article. I’m just totally ensure how you would call
    CreateShowMessageUsingCreateItem(OutlookApp As Outlook._Application)

    You mentioneed creating an instance of the Application class. Please could you show me this line of code.

  • Eugene Astafiev says:

    Hi Trevor,

    Nope. You are on the right avenue. I can’t find any sentence which states that you need to create an instance of the Application class. Instead, I have found the following:

    For demonstration purposes I create a MailItem object and then show it to the user. To get the code running, you merely need to pass an instance of the Application class to the CreateShowMessageUsingCreateItem and CreateShowMessageUsingItemsAdd methods.

    In Add-in Express and VSTO based add-in projects you don’t need to create an Application object programatically. Please see the OutlookApp property in case of Add-in Express based add-ins and Application in case of VSTO ones.

  • Trevor Yearwood says:

    Sorry me mistake, I was meant to say how do a create an instance of OutlookApp to be passed to CreateShowMessageUsingCreateItem

    Thanks for the speedy response.

  • Trevor Yearwood says:

    Also do you know how to disable the warning message that appears when you use the Save method. Sorry to be a pain.

  • Eugene Astafiev says:

    Hi Trevor,

    Typically you can use the new operator to create a new instance of the class in .net:

    Outlook.Application olApp = new Outlook.Application();

    Note, you need to add a reference to the Outlook interop before.

  • Eugene Astafiev says:

    Hi Trevor,

    It looks like you are interested in the Outlook Security Manager.

  • JD Brennan says:

    The C# and Add-in Express (using CreateItem method) fails with:

    The operation failed.

    The C# and Add-in Express (using Add method) fails with:

    Operation aborted (Exception from HRESULT: 0x800004004 (E_ABORT))

    We’ve recently transitioned from hosted Exchange to Office365 and
    that’s when the problem started. Any ideas?

  • Eugene Astafiev says:

    Hi JD,

    Did you try to debug? What line of code fires the exception?

  • RW says:

    Hi Eugene,

    I used your “VB.NET and Add-in Express (using CreateItem method)” method. It is working perfectly fine. But once it opens the Outlook message I cannot open a new Outlook mail. It locks Outlook app. If I had Outlook opened previously then I cannot navigate to my other Outlook mails after opening a message programmatically. How can I stop it doing that?
    Thanks in advance….!

  • Eugene Astafiev says:

    Hi RW,

    Do you display a newly created mail item to a user? Do you pass true to the Display method of the MailItem class?

  • JD Brennan says:

    >Did you try to debug? What line of code fires the exception?

    Yes, I’m running in the debugger. I get an exception on the line
    of code that calls CreateItem()

    mail = OutlookApp.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;

  • RW says:

    Hi Eugene,

    I figured that out. I was passing .Display(true)

    Would you be able to explain bit more on this line? What is this modal window?

    Thanks again….!!

  • Eugene Astafiev says:

    Hi RW,

    Good news! Thank you for letting us know.

    Please take a look at the Modal window article at for more information on this.

    Good luck with your add-in project! :-)

  • Eugene Astafiev says:

    Hi JD,

    Could you please send a sample add-in project which can reproduce the issue to the support e-mail address (see readme.txt)? I will try to reproduce the issue on our PCs.

  • Robert says:

    My code strucks at two lines

    1. OlookApp = new Outlook.Application(); – I tried this first as per your example but system does not go ahead of this line… so i tried to check if outlook is running or not and used below in case outlook is running.. no luck in both cases
    2. OlookApp = Marshal.GetActiveObject(“Outlook.Application”) as Outlook.Application;

    ============================== code snippet=========================================

    if (Process.GetProcessesByName(“OUTLOOK”).Count() > 0)
    {

    // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
    OlookApp = Marshal.GetActiveObject(“Outlook.Application”) as Outlook.Application;
    }
    else // if outlook is not running then create an instance
    {

    // If not, create a new instance of Outlook and log on to the default profile.
    OlookApp = new Outlook.Application();
    nmSpace = OlookApp.GetNamespace(“MAPI”);
    nmSpace = null; nmSpace.Logon(“”, “”, Missing.Value, Missing.Value);
    nmSpace = null;
    }

  • Andrei Smolin (Add-in Express Team) says:

    Hello Robert,

    If you develop an Outlook add-in, you should use the Outlook.Application that the add-in provides; in Add-in Express based add-ins, see the OutlookApp property of the add-in module. If you develop a standalone application, then provide the exception message.

  • Santanu says:

    Hello,

    I have a requirement where i need to make sure that the mail item gets displayed in the Inbox folder instead of Drafts as mentioned in your article. Can you please let me know what we should do for the same?

    Regards
    Vineet More

  • Andrei Smolin (Add-in Express Team) says:

    Hello Vineet,

    To get an email created in a given folder, get a MAPIFolder object representing that folder and call MAPIFolder.Items.Add().

  • Santanu says:

    Hello Andrei,

    Mail item got added to inbox but it is not showing in Inbox, whereas the Inbox is showing one unread message but i cannot read it as the content are not being displayed on the Inbox.

    Regards
    Vineet More

  • Andrei Smolin (Add-in Express Team) says:

    Hello Vineet,

    Switch to the UnRead view.

  • Eric To says:

    Is there a way to programmatically discard changes done to MailItem without the “Do you want to save prompt”?

  • Andrei Smolin (Add-in Express Team) says:

    Hello Eric,

    You could try to use MailItem.Close(Outlook.OlInspectorClose.olDiscard); see https://msdn.microsoft.com/en-us/library/office/ff860308(v=office.15).aspx. Alternatively, you can try Inspector.Close(Outlook.OlInspectorClose.olDiscard).

  • Joao says:

    Hi guys,

    I’m using this code:

    Application oApp = new Application();
    MailItem oMailItem = oApp.CreateItem(OlItemType.olMailItem) as MailItem;

    When I debug and run it in my machine, it works fine. When I publish it to the server the application is opened but the mailitem isn’t created giving the error:

    “Thread was being aborted”

    Any ideas?

    Thanks!

  • Andrei Smolin (Add-in Express Team) says:

    Hello Joao,

    I know Microsoft *did* not recommend installing Office on the server; please see an Office 2010 article at https://support.microsoft.com/en-us/help/257757/considerations-for-server-side-automation-of-office. Don’t know if they allow using Office 2013-2016-365 on the server. Anyway, this doesn’t seem to be a programming issue. I recommend that you talk to an administrator.

  • Björn Leppin says:

    Hi,

    thanks to you I got it. Here what I get, if some one need to open a OutlookCustomForm in VSTO C#:
    >> I used a btnClick Event in a RibbonControl >>
    Outlook.NameSpace nSpace = Globals.ThisAddIn.Application.GetNamespace(“MAPI”);
    Outlook.Folder mailList = nSpace.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox) as Outlook.Folder;
    Outlook.MailItem mailItem = mailList.Items.Add(“IPM.Note.MyCustomForm”) as Outlook.MailItem;
    mailItem.Display();

  • Pipe says:

    Hi. Is possible to paste an Excel range in Outlook email using Interop library? I suppose it’s neccesary to convert Excel range in HTML.

    Thanks a lot!

  • Andrei Smolin (Add-in Express Team) says:

    Hello Pipe,

    Start Word and open a test document, start Excel, start Macro Recorder in Excel, select a range, copy it, switch to Word, paste, switch to Excel, stop Macro Recorder and study the macro: it reveals what objects and methods to use when copying a range from Excel.

    Now start Macro Recorder in Word, perform the same steps and study the macro that shows what objects and methods to use when pasting a range to Word.

    When you understand what code to write to copy an Excel range to a Word document, replace Word with an open Outlook inspector, and and the test Word document with the Word.Document object obtained through Inspector.WordEditor.

Post a comment

Have any questions? Ask us right now!