Eugene Astafiev

How To: Create a new distribution list item in Outlook

Sometimes Outlook users need to send their e-mails to the same recipients. The Outlook Object Model provides the DistListItem class exactly for this task. The distribution list represents a group of contacts that are related in some way. Using distribution lists users can set the TO, CC and BCC fields and send e-mails as they normally do. Let’s consider in depth how to create a distribution list in your profile programmatically with VSTO and Add-in Express for Office and .net.

There is no difference between creating a single contact item or a distribution list item. Distribution lists are stored in the Contacts folder too (I mean personal distribution lists). Note, you can send them to others if needed. If you use an Exchange server in the profile, the Global Address List can contain global distribution lists. They are available to everyone connected to the Exchange server.

The process of creating Outlook distribution lists is fairly simple. Some time ago we discussed how to create a new contact item programmatically. The similar steps are used for creating distribution list items in Outlook:

      1. The simplest way is to use the CreateItem method of the Application class. This method accepts a constant from the OlItemType enumeration and returns a newly created distribution list.
      2. The Items class provides the Add method which does the job. A newly created distribution list is always created in the default Contacts folder regardless of the Items collection we use (frankly speaking, the collection may come from any folder).
      3. We can use a template for creating a new distribution list. The Application class has the CreateItemFromTemplate method for this task. In one of my previous articles I described how to create a message based on a template. The method accepts a string representing file path to the Outlook template (.oft) as a parameter. My tests against Outlook 2010 show that you can pass an msg file as a template too.

After we created a new distribution list we need to add some recipients to it. We do this using the AddMembers method of the DistListItem class. It accepts an instance of the Recipients class and doesn’t return anything. We can create a single instance of the Recipient class using the Outlook Object Model classes. But how can we create an instance of the Recipients class? There is no way. The fact is that the Outlook Object Model doesn’t provide any method for this. Starting from Outlook 2002 the AddMember method can be used for adding a singular recipient, as a workaround. In case of version-neutral interop libraries I suggest using the following approach:

      1. Create a new temporarily Outlook mail item.
      2. Get a recipients collection from the newly created mail item.
      3. Add recipients to the collection.
      4. Add the recipients collection to the distribution list.
      5. Delete the mail item object created on step 1.

I know it is a long way… But it works like charm in case of Outlook 2000.

Don’t forget to pass an instance of the Application class to the CreateNewDistributionList method if you want to get the code running correctly.

C# & Add-in Express:

private void CreateNewDistributionList(Outlook._Application OutlookApp)
{
    Outlook.NameSpace ns = null;
    Outlook.MAPIFolder folderContacts = null;
    Outlook.Items contactItems = null;           
    Outlook.MailItem mail = null;
    Outlook.Recipients listRecipients = null;
    Outlook.DistListItem distributionList = null;
    try
    {
        ns = OutlookApp.GetNamespace("MAPI");
        folderContacts = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);                
        contactItems = folderContacts.Items;
        // create a new e-mail message to access the recipients collection 
        mail = contactItems.Add(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
        listRecipients = mail.Recipients;
        listRecipients.Add("Andrei Smolin");
        listRecipients.Add("Eugene Astafiev");
        listRecipients.Add("Dmitry Kostochko");               
        if(!listRecipients.ResolveAll())
        {
            System.Windows.Forms.MessageBox.Show("There are no such contact names. "+
               "Please make sure that you have corresponding records in your address book",
               "Add-in Express", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }
        // create a new distribution list item
        distributionList = contactItems.Add(Outlook.OlItemType.olDistributionListItem) 
                                                              as Outlook.DistListItem;       
       // distributionList = OutlookApp.CreateItem(Outlook.OlItemType.olDistributionListItem) 
       //                                                            as Outlook.DistListItem;
       // distributionList = OutlookApp.CreateItemFromTemplate("D:\\Add-in Express Team.oft") 
       //                                                            as Outlook.DistListItem;        
        distributionList.DLName = "Add-in Express Team";                    
        distributionList.AddMembers(listRecipients);
        distributionList.Save();
        distributionList.Display(true);                
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message, 
           "An exception is thrown...", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        if (distributionList != null) Marshal.ReleaseComObject(distributionList);
        if (listRecipients != null) Marshal.ReleaseComObject(listRecipients);
        if (mail != null)
        {
            mail.Delete();
            Marshal.ReleaseComObject(mail);
        }
        if (contactItems != null) Marshal.ReleaseComObject(contactItems);
        if (folderContacts != null) Marshal.ReleaseComObject(folderContacts);
        if (ns != null) Marshal.ReleaseComObject(ns);
    }
}

C# & VSTO:

using System.Windows.Forms;
using System.Runtime.InteropServices;
//
private void CreateNewDistributionList(Outlook.Application Application)
{
    Outlook.NameSpace ns = null;
    Outlook.MAPIFolder folderContacts = null;
    Outlook.Items contactItems = null;
    Outlook.MailItem mail = null;
    Outlook.Recipients listRecipients = null;
    Outlook.DistListItem distributionList = null;
    try
    {
        ns = Application.GetNamespace("MAPI");
        folderContacts = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
        contactItems = folderContacts.Items;
        // create a new e-mail message to access the recipients collection 
        mail = contactItems.Add(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
        listRecipients = mail.Recipients;
        listRecipients.Add("Andrei Smolin");
        listRecipients.Add("Eugene Astafiev");
        listRecipients.Add("Dmitry Kostochko");
        if (!listRecipients.ResolveAll())
        {
            System.Windows.Forms.MessageBox.Show("There are no such contact names. " +
               "Please make sure that you have corresponding records in your address book",
               "Add-in Express", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }
        distributionList = contactItems.Add(Outlook.OlItemType.olDistributionListItem) 
                                                              as Outlook.DistListItem;
       // distributionList = OutlookApp.CreateItem(Outlook.OlItemType.olDistributionListItem) 
       //                                                            as Outlook.DistListItem;
       // distributionList = OutlookApp.CreateItemFromTemplate("D:\\Add-in Express Team.oft") 
       //                                                            as Outlook.DistListItem;
        distributionList.DLName = "Add-in Express Team";
        distributionList.AddMembers(listRecipients);
        distributionList.Save();
        distributionList.Display(true);
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message,
           "An exception is thrown...", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        if (distributionList != null) Marshal.ReleaseComObject(distributionList);
        if (listRecipients != null) Marshal.ReleaseComObject(listRecipients);
        if (mail != null)
        {
            mail.Delete();
            Marshal.ReleaseComObject(mail);
        }
        if (contactItems != null) Marshal.ReleaseComObject(contactItems);
        if (folderContacts != null) Marshal.ReleaseComObject(folderContacts);
        if (ns != null) Marshal.ReleaseComObject(ns);
    }
}

VB.NET & Add-in Express:

Private Sub CreateNewDistributionList(ByRef OutlookApp As Outlook._Application)
    Dim ns As Outlook.NameSpace = Nothing
    Dim folderContacts As Outlook.MAPIFolder = Nothing
    Dim contactItems As Outlook.Items = Nothing
    Dim mail As Outlook.MailItem = Nothing
    Dim listRecipients As Outlook.Recipients = Nothing
    Dim distributionList As Outlook.DistListItem = Nothing
    Try
        ns = OutlookApp.GetNamespace("MAPI")
        folderContacts = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)
        contactItems = folderContacts.Items
        ' create a new e-mail message to access the recipients collection 
        mail = contactItems.Add(Outlook.OlItemType.olMailItem)
        listRecipients = mail.Recipients
        listRecipients.Add("Andrei Smolin")
        listRecipients.Add("Eugene Astafiev")
        listRecipients.Add("Dmitry Kostochko")
        If Not listRecipients.ResolveAll() Then
            System.Windows.Forms.MessageBox.Show("There are no such contact names. " + _
               "Please make sure that you have corresponding records in your address book",
               "Add-in Express", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Return
        End If
        distributionList = contactItems.Add(Outlook.OlItemType.olDistributionListItem)
        ' distributionList = OutlookApp.CreateItem(Outlook.OlItemType.olDistributionListItem)
        ' distributionList = OutlookApp.CreateItemFromTemplate("D:\Add-in Express Team.oft")
        distributionList.DLName = "Add-in Express Team"
        distributionList.AddMembers(listRecipients)
        distributionList.Save()
        distributionList.Display(True)
    Catch ex As Exception
        System.Windows.Forms.MessageBox.Show(ex.Message,
           "An exception is thrown...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Finally
        If Not IsNothing(distributionList) Then Marshal.ReleaseComObject(distributionList)
        If Not IsNothing(listRecipients) Then Marshal.ReleaseComObject(listRecipients)
        If Not IsNothing(mail) Then
            mail.Delete()
            Marshal.ReleaseComObject(mail)
        End If
        If Not IsNothing(contactItems) Then Marshal.ReleaseComObject(contactItems)
        If Not IsNothing(folderContacts) Then Marshal.ReleaseComObject(folderContacts)
        If Not IsNothing(ns) Then Marshal.ReleaseComObject(ns)
    End Try
End Sub

VB.NET & VSTO:

Imports System.Windows.Forms
Imports System.Runtime.InteropServices
'
Private Sub CreateNewDistributionList(ByRef Application As Outlook.Application)
    Dim ns As Outlook.NameSpace = Nothing
    Dim folderContacts As Outlook.MAPIFolder = Nothing
    Dim contactItems As Outlook.Items = Nothing
    Dim mail As Outlook.MailItem = Nothing
    Dim listRecipients As Outlook.Recipients = Nothing
    Dim distributionList As Outlook.DistListItem = Nothing
    Try
        ns = Application.GetNamespace("MAPI")
        folderContacts = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)
        contactItems = folderContacts.Items
        ' create a new e-mail message to access the recipients collection 
        mail = contactItems.Add(Outlook.OlItemType.olMailItem)
        listRecipients = mail.Recipients
        listRecipients.Add("Andrei Smolin")
        listRecipients.Add("Eugene Astafiev")
        listRecipients.Add("Dmitry Kostochko")
        If Not listRecipients.ResolveAll() Then
            System.Windows.Forms.MessageBox.Show("There are no such contact names. " + _
               "Please make sure that you have corresponding records in your address book",
               "Add-in Express", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Return
        End If
        distributionList = contactItems.Add(Outlook.OlItemType.olDistributionListItem)
        ' distributionList = OutlookApp.CreateItem(Outlook.OlItemType.olDistributionListItem)
        ' distributionList = OutlookApp.CreateItemFromTemplate("D:\Add-in Express Team.oft")
        distributionList.DLName = "Add-in Express Team"
        distributionList.AddMembers(listRecipients)
        distributionList.Save()
        distributionList.Display(True)
    Catch ex As Exception
        System.Windows.Forms.MessageBox.Show(ex.Message,
          "An exception is thrown...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Finally
        If Not IsNothing(distributionList) Then Marshal.ReleaseComObject(distributionList)
        If Not IsNothing(listRecipients) Then Marshal.ReleaseComObject(listRecipients)
        If Not IsNothing(mail) Then
            mail.Delete()
            Marshal.ReleaseComObject(mail)
        End If
        If Not IsNothing(contactItems) Then Marshal.ReleaseComObject(contactItems)
        If Not IsNothing(folderContacts) Then Marshal.ReleaseComObject(folderContacts)
        If Not IsNothing(ns) Then Marshal.ReleaseComObject(ns)
    End Try
End Sub

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

17 Comments

  • Michael Melio says:

    Very helpful, thanks!

  • Mario says:

    Thank you very much!! It works perfectly

  • David Ralph says:

    I found your post on line. I’ve used several of the concepts to create the programing I need. i am trying to create and populate a distribution list but I’m finding that the Outlook.MAPIFolder is not available in my version of VBA.

    Is there a work around for this?

    Also, it looks like the program wants to use contacts in the local contcts list (default folder). I need to use a global list. Any suggestions?

    Thanks,
    dgr

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

    Hello David,

    On Outlook.MAPIFolder. You can just print dim aFolder as Outlook.MAPIFolder in the IDE. Compiling this declaration produces an error only if there’s no Outlook reference in your project. Or, you can use dim aFolder as Outlook.Folder instead.

    Instead of using e.g. listRecipients.Add(“Andrei Smolin”), you can start with retrieving the AddressList object representing the required address book: walk through ns.AddressLists and check ns.AddressLists.Item(indexAL).Name. Then, for each anAdLstEntry=theAddressList.AddressEntries.Item(indexAE) which meets your requirements, you call listRecipients.Add anAdLstEntry.GetContact.FileAs.

  • Taq says:

    Hi, can you tell me in wich propertie can i store an integer number to use it like a key?
    I need to link address email stored into my database with outlook accounts and to link distribution lists so i think that i can to do this saving a key into same propertie of distribution list but i don’t know where.
    Thank you

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

    DistListItem allows creating a UserProperty and you can use such a UserProperty to store the key. See how to create a UserProperty at https://www.add-in-express.com/creating-addins-blog/how-to-add-a-custom-property-to-the-userproperties-collection-of-an-e-mail-item-in-outlook/.

  • antonio says:

    But if there is already a distribution list named “foo” with some members
    How can I delete it?

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

    Hello Antonio,

    You can use DistListItem.Delete(), see https://msdn.microsoft.com/en-us/library/office/ff869885%28v=office.15%29.aspx.

  • LedHed says:

    Is it possible to add a DistributionList to another DistributionList?
    When I create a recipient with the name of a distribution list and resolve it, then add it to an existing distribution list, It adds a recipient object (like a standard contact) instead of the Distribution List. Any help is appreciated.

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

    Hello LedHed,

    The code above modified so that it adds an existing DL to the list of recipients and creates a DL with a new name works fine for me. It does create the new DL and I can use it in the To field as expected. Do you add the DL to the same DL?

  • LedHed says:

    Andrei,

    Thanks for the quick reply. I used similar code to yours (VB.NET)
    distributionList = contactItems.Add(Outlook.OlItemType.olDistributionListItem)
    ‘ distributionList = OutlookApp.CreateItem(Outlook.OlItemType.olDistributionListItem)
    ‘ distributionList = OutlookApp.CreateItemFromTemplate(“D:\Add-in Express Team.oft”)
    distributionList.DLName = “Add-in Express Team”
    distributionList.AddMembers(listRecipients)
    distributionList.Save()

    But the distribution list I’m trying to add isn’t in the GAL its in the Outlook Contacts folder. GAL distribution lists do resolve and are added correctly.

    So I guess I should restate my question. Is there a way to add a Outlook “contact group” to another “contact group”. [ Both groups exist in the ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts) ]

    Thanks.

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

    I suppose what I don’t understand is this part: “It adds a recipient object (like a standard contact) instead of the Distribution List”.

    The following code adds a recipient to the Recipients collection which is then passed to DistListItem.AddMembers(); “Add-in Express Team” is the name of the DistListItem created as shown in the article above.

    mail = contactItems.Add(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
    listRecipients = mail.Recipients;
    listRecipients.Add(“Add-in Express Team”);
    if (!listRecipients.ResolveAll()) { …
    }
    distributionList = contactItems.Add(Outlook.OlItemType.olDistributionListItem)
    as Outlook.DistListItem;
    distributionList.DLName = “Add-in Express Team 2”;
    distributionList.AddMembers(listRecipients);

    This code works whether the Contact folder is on Exchange or PST.

    Now, if I add the second DL to the To filed and expand it, Outlook replaces the To field with recipients of the DL. Since the list of recipients includes the first DL, I can expand it thus placing the recipients from the first DL into the To field.

  • LedHed says:

    What I mean by “It adds a recipient object (like a standard contact) instead of the Distribution List”, is that if I edit said object it opens as a contact not a Group or DL.

  • LedHed says:

    No, I’m not adding the DL to itself.

    The way my code works is as it loops through a CSV file, when it finds a group it creates it (Call it GroupA). Then it loops through the members of GroupA and adds recipients to it. While its looping through the members of GroupA, if it comes across another group (Call it GroupB) its supposed to add GroupB to GroupA.

    If your code works then clearly there is something wrong with mine. I appreciate your help.

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

    > What I mean by “It adds a recipient object (like a standard contact) instead of the Distribution List”, is that if I edit said object it opens as a contact not a Group or DL.

    It sounds like you have a contact and a distribution list of the same name. Please have a look at https://social.msdn.microsoft.com/Forums/en-US/93f70e63-aae3-46c8-8438-02a4354f2d56/outlook-2010-cant-resolve-certain-exchange-server-2010-addresses-why?forum=outlookdev.

  • Pratima says:

    I am creating an outlook add-in. I can read the email address from TO, CC, and BCC. But, the problem is when my TO contains Group List it does not display. How can I read all the email address that my Group List contains?

    Any help is appreciated.

    With Best Regards.

Post a comment

Have any questions? Ask us right now!