Eugene Astafiev

How To: Create a new folder in Outlook

    Today I will show you how to create a new folder in Outlook. As you have probably noticed, the Outlook Object Model provides the Add function of the Folders class. You can get an instance of the Folders class using the Folders property of the Folder class in Outlook. And this is exactly what we need to implement the required functionality.
    The first parameter of the Add function accepts a string which contains the display name of the new folder. The second parameter accepts the OlDefaultFolders enumeration that indicates the type of folder you want to create. If the new folder type is not specified, it will default to the type of the folder in which it is created. The following values are possible for the second parameter: olFolderCalendar, olFolderContacts, olFolderDrafts, olFolderInbox, olFolderJournal, olFolderNotes and olFolderTasks. Note, the second parameter is optional. Say, if you want to create a subfolder with the parent folder type, you can omit the second parameter.
    The sample code you see below creates a subfolder in the Inbox folder. To get the code running you need to pass an instance of the Outlook Application class to the CreateInboxSubfolder method. In Add-in Express based add-ins you can retrieve it using the OutlookApp property of the add-in module and in VSTO based add-ins please use the Application property of the add-in class. So, let's get to work!
    C# and Add-in Express:
private void CreateInboxSubFolder(Outlook.Application OutlookApp)
{
      Outlook.NameSpace nameSpace = OutlookApp.GetNamespace("MAPI");
      Outlook.MAPIFolder folderInbox = nameSpace.GetDefaultFolder(
            Outlook.OlDefaultFolders.olFolderInbox);
      Outlook.Folders inboxFolders = folderInbox.Folders;
      Outlook.MAPIFolder subfolderInbox = null;
      try
      {
            subfolderInbox = inboxFolders.Add("InboxSubfolder", 
                 Outlook.OlDefaultFolders.olFolderInbox);
      }
      catch (COMException exception)
      {
            if (exception.ErrorCode == -2147352567)
                 //  Cannot create the folder.
                 System.Windows.Forms.MessageBox.Show(exception.Message);
       }
       if (subfolderInbox != null) Marshal.ReleaseComObject(subfolderInbox);
       if (inboxFolders != null) Marshal.ReleaseComObject(inboxFolders);
       if (folderInbox != null) Marshal.ReleaseComObject(folderInbox);
       if (nameSpace != null) Marshal.ReleaseComObject(nameSpace);
}
    VB.NET and Add-in Express:
Private Sub CreateInboxSubFolder(OutlookApp As Outlook.Application)
     Dim mapiNameSpace As Outlook.NameSpace = OutlookApp.GetNamespace("MAPI")
     Dim folderInbox As Outlook.MAPIFolder = mapiNameSpace.GetDefaultFolder(
           Outlook.OlDefaultFolders.olFolderInbox)
     Dim inboxFolders As Outlook.Folders = folderInbox.Folders
     Dim subfolderInbox As Outlook.MAPIFolder = Nothing
     Try
          subfolderInbox = inboxFolders.Add("InboxSubfolder", 
               Outlook.OlDefaultFolders.olFolderInbox)
     Catch ex As COMException
         If (ex.ErrorCode = -2147352567) Then
              ' Cannot create the folder.
              System.Windows.Forms.MessageBox.Show(ex.Message)
         End If
     End Try
     If Not IsNothing(subfolderInbox) Then Marshal.ReleaseComObject(subfolderInbox)
     If Not IsNothing(inboxFolders) Then Marshal.ReleaseComObject(inboxFolders)
     If Not IsNothing(folderInbox) Then Marshal.ReleaseComObject(folderInbox)
     If Not IsNothing(mapiNameSpace) Then Marshal.ReleaseComObject(mapiNameSpace)
End Sub
    C# and VSTO:
using System.Runtime.InteropServices;
// …
private void CreateInboxSubFolder(Outlook.Application application)
{
     Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
     Outlook.MAPIFolder folderInbox =
     nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
     Outlook.Folders inboxFolders = folderInbox.Folders;
     Outlook.MAPIFolder subfolderInbox = null;
     try
    {
           subfolderInbox = inboxFolders.Add("InboxSubfolder", 
                Outlook.OlDefaultFolders.olFolderInbox);
     }
     catch (COMException exception)
     {
            if (exception.ErrorCode == -2147352567)
                   //  Cannot create the folder.
                   System.Windows.Forms.MessageBox.Show(exception.Message);
      }
      if (subfolderInbox != null) Marshal.ReleaseComObject(subfolderInbox);
      if (inboxFolders != null) Marshal.ReleaseComObject(inboxFolders);
      if (folderInbox != null) Marshal.ReleaseComObject(folderInbox);
      if (nameSpace != null) Marshal.ReleaseComObject(nameSpace);
}
    VB.NET and VSTO:
Imports System.Runtime.InteropServices
' …
Private Sub CreateInboxSubFolder(Application As Outlook.Application)
     Dim mapiNameSpace As Outlook.NameSpace = Application.GetNamespace("MAPI")
     Dim folderInbox As Outlook.MAPIFolder = mapiNameSpace.GetDefaultFolder(
            Outlook.OlDefaultFolders.olFolderInbox)
     Dim inboxFolders As Outlook.Folders = folderInbox.Folders
     Dim subfolderInbox As Outlook.MAPIFolder = Nothing
     Try
          subfolderInbox = inboxFolders.Add("InboxSubfolder", 
                Outlook.OlDefaultFolders.olFolderInbox)
     Catch ex As COMException
          If (ex.ErrorCode = -2147352567) Then
                '  Cannot create the folder. 
                System.Windows.Forms.MessageBox.Show(ex.Message)
          End If
     End Try
     If Not IsNothing(subfolderInbox) Then Marshal.ReleaseComObject(subfolderInbox)
     If Not IsNothing(inboxFolders) Then Marshal.ReleaseComObject(inboxFolders)
     If Not IsNothing(folderInbox) Then Marshal.ReleaseComObject(folderInbox)
     If Not IsNothing(mapiNameSpace) Then Marshal.ReleaseComObject(mapiNameSpace)
End Sub
    A message box will inform the user if such folder already exists. See you on our forums and in the e-mail support!

10 Comments

  • Kiran says:

    Microsoft.Office.Interop.Outlook.Application objOutlookApplication = new Microsoft.Office.Interop.Outlook.Application();
    Microsoft.Office.Interop.Outlook.

    NameSpace objNamespace = objOutlookApplication.GetNamespace(“MAPI”);
    Microsoft.Office.Interop.Outlook.MAPIFolder objMAPIFolder = null;

    try

    {

    objMAPIFolder = (MAPIFolder)objNamespace.OpenSharedFolder(@”\AppData\Local\Microsoft\Outlook\abc”, null, null, null);

    Folder objFolder = (Folder)objNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
    string name = objFolder.FullFolderPath;

    }

    catch (StackOverflowException ex)

    {

    // MessageBox.Show(e.Message);

    }

    following error i am getting

    System.Runtime.InteropServices.COMException was unhandled
    Message=”Invalid shared folder.”
    Source=”Microsoft Outlook”
    ErrorCode=-2147352567
    StackTrace:
    at Microsoft.Office.Interop.Outlook.NameSpaceClass.OpenSharedFolder(String Path, Object Name, Object DownloadAttachments, Object UseTTL)
    at WindowsApplication1.ReadOST.btnOSTRead_Click(Object sender, EventArgs e) in \WindowsApplication1\WindowsApplication1\ReadOST.cs:line 37
    at System.Windows.Forms.Control.OnClick(EventArgs e)
    at System.Windows.Forms.Button.OnClick(EventArgs e)
    at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
    at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
    at System.Windows.Forms.Control.WndProc(Message& m)
    at System.Windows.Forms.ButtonBase.WndProc(Message& m)
    at System.Windows.Forms.Button.WndProc(Message& m)
    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
    at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
    at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
    at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
    at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
    at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
    at System.Windows.Forms.Application.Run(Form mainForm)
    at WindowsApplication1.Program.Main() in \WindowsApplication1\WindowsApplication1\Program.cs:line 17
    at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
    at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
    at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    at System.Threading.ThreadHelper.ThreadStart()

  • Eugene Astafiev says:

    Hi Kiran,

    It looks like the following line of code throws the exception. Am I right?

    objMAPIFolder = (MAPIFolder)objNamespace.OpenSharedFolder(
            @”\AppData\Local\Microsoft\Outlook\abc”, null, null, null);

    Most probably you passed a wrong value to the OpenSharedFolder method of the Namespace class. Do you pass a file path as the first parameter?

    May be you are trying to open an Outlook store instead? If so, please take a look at the How To: Create a new Outlook Personal Folders store and add it to the current profile article.

  • Jeannine says:

    this works and is based on the samples from Visual Studio 2010 and Eugene’s code. This has to be run on a machine that has Outlook.

    /********************************** Module Header **********************************\
    * Module Name: Program.cs
    * Project: CSAutomateOutlook
    * Copyright (c) Microsoft Corporation.
    *
    * The CSAutomateOutlook example demonstrates the use of Visual C# code to automate
    * Microsoft Outlook to log on with your profile, enumerate contacts, send a mail, log
    * off, close the Microsoft Outlook application and then clean up unmanaged COM
    * resources.
    *
    * This source is subject to the Microsoft Public License.
    * See https://www.microsoft.com/en-us/openness/resources/licenses.aspx#MPL.
    * All other rights reserved.
    *
    * THIS CODE AND INFORMATION IS PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
    * EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
    * MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
    \***********************************************************************************/

    #region Using directives
    using System;
    using System.Runtime.InteropServices;
    using Outlook = Microsoft.Office.Interop.Outlook;
    #endregion

    namespace CSAutomateOutlook
    {
    class Program
    {
    [STAThread]
    static void Main(string[] args)
    {
    AutomateOutlook();

    // Clean up the unmanaged Outlook COM resources by forcing a garbage
    // collection as soon as the calling function is off the stack (at which
    // point these objects are no longer rooted).

    GC.Collect();
    GC.WaitForPendingFinalizers();
    // GC needs to be called twice in order to get the Finalizers called –
    // the first time in, it simply makes a list of what is to be finalized,
    // the second time in, it actually is finalizing. Only then will the
    // object do its automatic ReleaseComObject.
    GC.Collect();
    GC.WaitForPendingFinalizers();
    }

    private void CreateInboxSubFolder(Outlook.Application OutlookApp)
    {
    Outlook.NameSpace nameSpace = OutlookApp.GetNamespace(“MAPI”);
    Outlook.MAPIFolder folderInbox = nameSpace.GetDefaultFolder(
    Outlook.OlDefaultFolders.olFolderInbox);
    Outlook.Folders inboxFolders = folderInbox.Folders;
    Outlook.MAPIFolder subfolderInbox = null;
    try
    {

    for (int i = 4; i <= 1000 ; i++)
    {
    String folderName = i.ToString("D6");
    subfolderInbox = inboxFolders.Add(folderName, Outlook.OlDefaultFolders.olFolderInbox);
    }

    }
    catch (COMException exception)
    {
    if (exception.ErrorCode == -2147352567)
    // Cannot create the folder.
    Console.WriteLine(exception.Message);

    }
    if (subfolderInbox != null) Marshal.ReleaseComObject(subfolderInbox);
    if (inboxFolders != null) Marshal.ReleaseComObject(inboxFolders);
    if (folderInbox != null) Marshal.ReleaseComObject(folderInbox);
    if (nameSpace != null) Marshal.ReleaseComObject(nameSpace);
    }

    static void AutomateOutlook()
    {
    object missing = Type.Missing;

    Outlook.Application oOutlook = null;
    Outlook.NameSpace oNS = null;
    Outlook.Folder oCtFolder = null;
    Outlook.Items oCts = null;
    Outlook.MailItem oMail = null;

    try
    {
    // Start Microsoft Outlook and log on with your profile.

    // Create an Outlook application.
    oOutlook = new Outlook.Application();
    Console.WriteLine("Outlook.Application is started");

    Console.WriteLine("User logs on …");

    // Get the namespace.
    oNS = oOutlook.GetNamespace("MAPI");

    // Log on by using a dialog box to choose the profile.
    oNS.Logon(missing, missing, true, true);

    // Alternative logon method that uses a specific profile.
    // If you use this logon method, change the profile name to an
    // appropriate value. The second parameter of Logon is the password
    // (if any) associated with the profile. This parameter exists only
    // for backwards compatibility and for security reasons, and it is
    // not recommended for use.
    //oNS.Logon("YourValidProfile", missing, false, true);

    Console.WriteLine("Press ENTER to continue when Outlook is ready.");
    Console.ReadLine();

    Outlook.NameSpace nameSpace = oOutlook.GetNamespace("MAPI");
    Outlook.MAPIFolder folderInbox = nameSpace.GetDefaultFolder(
    Outlook.OlDefaultFolders.olFolderInbox);
    Outlook.Folders inboxFolders = folderInbox.Folders;
    Outlook.MAPIFolder subfolderInbox = null;

    for (int i = 4; i <= 1000; i++)
    {
    String folderName = i.ToString("D6");
    subfolderInbox = inboxFolders.Add(folderName, Outlook.OlDefaultFolders.olFolderInbox);
    }

    //old code wqorks !!!! keep this subfolderInbox = inboxFolders.Add("InboxSubfolder", Outlook.OlDefaultFolders.olFolderInbox);

    if (subfolderInbox != null) Marshal.ReleaseComObject(subfolderInbox);
    if (inboxFolders != null) Marshal.ReleaseComObject(inboxFolders);
    if (folderInbox != null) Marshal.ReleaseComObject(folderInbox);
    if (nameSpace != null) Marshal.ReleaseComObject(nameSpace);

    // Enumerate the contact items.

    Console.WriteLine("Enumerate the contact items");

    oCtFolder = (Outlook.Folder)oNS.GetDefaultFolder(
    Outlook.OlDefaultFolders.olFolderContacts);
    oCts = oCtFolder.Items;

    // Enumerate the contact items. Be careful with foreach loops.
    // See: https://tiny.cc/uXw8S.
    for (int i = 1; i <= oCts.Count; i++)
    {
    object oItem = oCts[i];

    if (oItem is Outlook.ContactItem)
    {
    Outlook.ContactItem oCt = (Outlook.ContactItem)oItem;
    Console.WriteLine(oCt.Email1Address);
    // Do not need to Marshal.ReleaseComObject oCt because
    // (Outlook.ContactItem)oItem is a simple .NET type
    // casting, instead of a COM QueryInterface.
    }
    else if (oItem is Outlook.DistListItem)
    {
    Outlook.DistListItem oDl = (Outlook.DistListItem)oItem;
    Console.WriteLine(oDl.DLName);
    // Do not need to Marshal.ReleaseComObject oDl because
    // (Outlook.DistListItem)oItem is a simple .NET type
    // casting, instead of a COM QueryInterface.
    }

    // Release the COM object of the Outlook item.
    Marshal.FinalReleaseComObject(oItem);
    oItem = null;
    }

    // Create and send a new mail item.

    Console.WriteLine("Create and send a new mail item");

    oMail = (Outlook.MailItem)oOutlook.CreateItem(
    Outlook.OlItemType.olMailItem);

    // Set the properties of the email.
    oMail.Subject = "Feedback of All-In-One Code Framework";
    oMail.To = "codefxf@microsoft.com";
    oMail.HTMLBody = "Feedback:“;

    // Displays a new Inspector object for the item and allows users to
    // click on the Send button to send the mail manually.
    // Modal = true makes the Inspector window modal
    oMail.Display(true);
    // [-or-]
    // Automatically send the mail without a new Inspector window.
    //((Outlook._MailItem)oMail).Send();

    // User logs off and quits Outlook.

    Console.WriteLine(“Log off and quit the Outlook application”);
    oNS.Logoff();
    ((Outlook._Application)oOutlook).Quit();
    }
    catch (Exception ex)
    {
    Console.WriteLine(“AutomateOutlook throws the error: {0}”, ex.Message);
    }
    finally
    {
    // Manually clean up the explicit unmanaged Outlook COM resources by
    // calling Marshal.FinalReleaseComObject on all accessor objects.
    // See https://support.microsoft.com/kb/317109.

    if (oMail != null)
    {
    Marshal.FinalReleaseComObject(oMail);
    oMail = null;
    }
    if (oCts != null)
    {
    Marshal.FinalReleaseComObject(oCts);
    oCts = null;
    }
    if (oCtFolder != null)
    {
    Marshal.FinalReleaseComObject(oCtFolder);
    oCtFolder = null;
    }
    if (oNS != null)
    {
    Marshal.FinalReleaseComObject(oNS);
    oNS = null;
    }
    if (oOutlook != null)
    {
    Marshal.FinalReleaseComObject(oOutlook);
    oOutlook = null;
    }
    }
    }
    }
    }

  • Eugene Astafiev says:

    Hi Jeannine,

    Could you please describe the issue? Do you get any error or exceptions?

  • ilazar319 says:

    Hi, I’m new to VSTOs and am using Vis Studio 2017 (Office 2013). Basically I work in a project environment where every project needs the same folder structure to sift emails into and so want to make a ribbon button.

    I have a working VBA version and am trying to move it to VB .NET. I’ve tried to adapt some things per your section “VB.NET & VSTO” above but am getting an error on the first line:

    Dim myNameSpace As Outlook.NameSpace = Application.GetNamespace(“MAPI”)

    Error is: ‘Application’ is not declared. It may be inaccessible due to its protection level.

    I’ve tried a few different variations and nothing works – any thoughts?

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

    Hello ilazar319,

    Use Globals.ThisAddIn.Application instead.

  • TAYYABA says:

    kindly help me i want to read the file within the attached folder in the inbox folder of outlook

    thanks in advance

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

    Hello TAYYABA,

    You get an Outlook.MAPIFolder object representing the Inbox folder via Namespace.GetDefaultFolder(…). You call {a MAPIFolder object}.Folders to get the object representing a collection of all subfolders of the specified folder. The Folders collection lets you use an enumerator: in C# – {a Folders object}[i] or {Folders}[“%folder name%”], in VB.NET – {a Folders object}.Item(i) or {Folders}.Item(“%folder name%”). When you have a MAPIFolder object representing the folder that you need, call {a MAPIFolder object}.Items to get the collection of all items in that folder. You may want to use Items.Find/Items.Restrict to filter the items and get a [smaller] collection of items. Scan the collection, find the item(s) you need, cast it to Outlook.MailItem (or e.g. Outlook.ContctItem, TaskItem, etc.) get the Attachments collection and scan it. When you get an attachment that you need, save the attachemtn using Attachment.SaveToFile() and read the file.

    All if these calls are described in the Outlook object model at https://docs.microsoft.com/en-us/office/vba/api/overview/outlook.

  • Harsha says:

    Hi, How can I create a parent folder I Don’t want to create for a subfolder.

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

    Hello Harsha,

    Every folder is a child folder of some other folder. So, you need to find a folder in which to create your folder.

Post a comment

Have any questions? Ask us right now!