Create a distribution list

This example shows how to create a distribution list and display it to the user.

Example

Note

The following code example is an excerpt from Programming Applications for Microsoft Office Outlook 2007.

In the following code example, CreateDistributionList creates a distribution list by calling the CreateItem(OlItemType) method to create a DistListItem object. Next it creates a Table object, and calls the GetTable(Object, Object) method to find all contacts in the default Contacts folder for which the Subject property value is “Top Customer” and the Email1Address property value is not empty. Once all contacts are identified, the Email1Address name is added as a column to the Table. CreateDistributionList then creates a Recipient object by using the CreateRecipient(String) method from the NameSpace object. CreateDistributionList finally displays the “Top Customers” distribution list to the user.

Note

You must pass a resolved Recipient object as a parameter to the AddMember(Recipient) method of the DistListItem object. To resolve a Recipient object, use the Resolve() method.

If you use Visual Studio to test this code example, you must first add a reference to the Microsoft Outlook 15.0 Object Library component and specify the Outlook variable when you import the Microsoft.Office.Interop.Outlook namespace. The using statement must not occur directly before the functions in the code example but must be added before the public Class declaration. The following line of code shows how to do the import and assignment in C#.

using Outlook = Microsoft.Office.Interop.Outlook;
private void CreateDistributionList()
{
    Outlook.DistListItem distList = Application.CreateItem(
        Outlook.OlItemType.olDistributionListItem)
        as Outlook.DistListItem;
    distList.Subject = "Top Customers";
    //Find top customer category in Contacts folder
    string filter = "[Categories] = 'Top Customer'"
        + " AND [Email1Address] <> ''";
    Outlook.Table table =
        Application.Session.GetDefaultFolder
        (Outlook.OlDefaultFolders.olFolderContacts).
        GetTable(filter, Outlook.OlTableContents.olUserItems);
    table.Columns.Add("Email1Address");
    while (!table.EndOfTable)
    {
        Outlook.Row nextRow = table.GetNextRow();
        Outlook.Recipient recip =
            Application.Session.CreateRecipient(
            nextRow["Email1Address"].ToString());
        //Resolve the Recipient before calling AddMember
        recip.Resolve();
        distList.AddMember(recip);
    }
    distList.Display(false);
}

See also