Pieter van der Westhuizen

How to create custom Outlook rules and execute them programmatically: C# example

The Microsoft Outlook Rules is a very powerful feature that can sometimes get lost amongst the myriad other features and abilities of Outlook. Many Outlook programmers do not realise that Microsoft introduced a new rules object model in Outlook 2007 allowing developers to harness the power of Outlook rules.

In this article we’ll explore aspects of the rule object model and I’ll show you how to create your own rule and how to execute rules on demand on any folder in Outlook 2007, 2010 and 2013.

Creating the Outlook add-in project in Visual Studio

We’ll start by creating a new ADX COM Add-in project in Visual Studio 2012 with Add-in Express for Office and .net. If you’re wondering why my Visual Studio 2012′s colour scheme looks different than the default colour scheme, have a look at the Visual Studio 2012 Color Theme Editor.

Creating a new Outlook COM Add-in project in Visual Studio 2012

Next, select your programming language (its C# for this project), minimum supported version of Office (I’m selecting Office 2007, since the new rules object model was only introduced in Outlook 2007, and my plug-in will work in Outlook 2007, 2010 and 2013) and Microsoft Outlook as the supported application and finish the wizard.

Selecting a programming language, minimum supported version of Office and Outlook as the supported application

Creating the Outlook rule programmatically

Programmatically creating an Outlook rule is pretty straight-forward once you understand the object hierarchy and how all the pieces fit together. All the current users’ rules are stored in the Store objects’ Rules collection property. Each Rule within the Rules collection has a collection of RuleActions and RuleConditions.

In this example we’ll create a rule that will check for all mail items in a folder that contains the words “Order” or “Orders” and then move those mail items to a sub-folder in our Outlook root folder.

The following code first checks whether our Rule already exists, if not, we then check whether the destination “Orders” folder exists and if it does not exist, we create it. We then get a reference to the Outlook Rules collection and create our rule, its conditions and actions. You’ll need to wrap it inside a try-catch as the GetRules() method of the Store object will raise an exception if the user is not connected to Microsoft Exchange or if they are disconnected.


private void AddinModule_AddinStartupComplete(object sender, EventArgs e)
{
    Outlook.NameSpace session = null;
    Outlook.Store store = null;
    Outlook.Rules rules = null;
    Outlook.MAPIFolder destinationFolder = null;
    Outlook.MAPIFolder rootFolder = null;
    Outlook.Folders rootFolderFolders = null;

    Outlook.Rule rule = null;
    Outlook.RuleConditions ruleConditions = null;
    Outlook.TextRuleCondition subjectTextRuleCondition = null;

    Outlook.RuleActions ruleActions = null;
    Outlook.MoveOrCopyRuleAction moveRuleAction=null;                       

    string ruleName = string.Empty;

    try
    {
        ruleName = "Move Order Mails Rule";
        session = OutlookApp.Session;
        store = session.DefaultStore;
        rules = store.GetRules();

        if (!RuleExist(ruleName, rules))
        {
            rootFolder = store.GetRootFolder();
            destinationFolder = GetFolder(rootFolder.FolderPath + "\\Orders",this.OutlookApp);

            if (destinationFolder == null)
            {
                rootFolderFolders = rootFolder.Folders;
                destinationFolder = rootFolderFolders.Add("Orders");
            }

            rule = rules.Create(ruleName, Outlook.OlRuleType.olRuleReceive);
            ruleConditions = rule.Conditions;

            subjectTextRuleCondition = ruleConditions.Subject;
            subjectTextRuleCondition.Text = new string[]
				{ "Orders", "orders", "Order", "order" };
            subjectTextRuleCondition.Enabled = true;

            ruleActions = rule.Actions;
            moveRuleAction = ruleActions.MoveToFolder;
            moveRuleAction.Folder = destinationFolder;
            moveRuleAction.Enabled = true;
                    
            ruleActions.DesktopAlert.Enabled = true;

            rules.Save(true);
        }
        LoadRules();
    }
    catch (Exception ex)
    {
        Debug.Write(ex.Message);
    }
    finally
    {
        if (moveRuleAction != null)
            Marshal.ReleaseComObject(moveRuleAction);
        if (ruleActions != null)
            Marshal.ReleaseComObject(ruleActions);
        if (subjectTextRuleCondition != null)
            Marshal.ReleaseComObject(subjectTextRuleCondition);
        if (ruleConditions != null)
            Marshal.ReleaseComObject(ruleConditions);
        if (rule != null)
            Marshal.ReleaseComObject(rule);
        if (rootFolderFolders != null)
            Marshal.ReleaseComObject(rootFolderFolders);
        if (rootFolder != null)
            Marshal.ReleaseComObject(rootFolder);
        if (destinationFolder != null)
            Marshal.ReleaseComObject(destinationFolder);
        if (rules != null)
            Marshal.ReleaseComObject(rules);
        if (store != null)
            Marshal.ReleaseComObject(store);
        if (session != null)
            Marshal.ReleaseComObject(session);
    }
}

The LoadRules() method loads all Outlook rules into a Ribbon combo-box, and the code listing for this method is as follows:


private void LoadRules()
{
    Outlook.NameSpace session = null;
    Outlook.Store store = null;
    Outlook.Rules rules = null;

    try
    {
        session = OutlookApp.Session;
        store = session.DefaultStore;
        rules = store.GetRules();

        for (int i = 1; i <= rules.Count; i++)
        {
            Outlook.Rule rule = rules[i];
            ADXRibbonItem item = new ADXRibbonItem();
            item.Caption = rule.Name;
            ruleNamesRibbonComboBox.Items.Add(item);
        }
    }
    finally
    {
        if (rules != null)
            Marshal.ReleaseComObject(rules);
        if (store != null)
            Marshal.ReleaseComObject(store);
        if (session != null)
            Marshal.ReleaseComObject(session);
    }
}

Running your custom Outlook rule on demand

Now that we've created the rule, let's add functionality that will allow the user to run any custom Outlook rule on demand for the current folder. To do this, we need to add a new ADXRibbonTab control to the design surface of the AddinModule designer, and design its layout to resemble the following image:

Designing the layout of the custom Outlook ribbon tab

Add the following code to the buttons' OnClick event:


private void runRuleRibbonButton_OnClick(object sender, IRibbonControl control, bool pressed)
{
    Outlook.Explorer currExplorer = null;
    Outlook.MAPIFolder currFolder = null;
    Outlook.NameSpace session = null;
    Outlook.Store defaultStore = null;

    Outlook.Rules rules = null;
    Outlook.Rule selectedRule = null;

    try
    {
        currExplorer = OutlookApp.ActiveExplorer();
        currFolder = currExplorer.CurrentFolder;
        session = currExplorer.Session;
        defaultStore = session.DefaultStore;
        rules = defaultStore.GetRules();

        selectedRule = rules[ruleNamesRibbonComboBox.Text];

        if (selectedRule != null)
        {
            selectedRule.Execute(true,
				currFolder,
				includeSubFoldersRibbonCheckBox.Pressed,
				Outlook.OlRuleExecuteOption.olRuleExecuteAllMessages);
        }
    }
    catch (Exception ex)
    {
        Debug.Write(ex.Message);
    }
    finally
    {
        if (selectedRule != null)
            Marshal.ReleaseComObject(selectedRule);
        if (rules != null)
            Marshal.ReleaseComObject(rules);
        if (defaultStore != null)
            Marshal.ReleaseComObject(defaultStore);
        if (session != null)
            Marshal.ReleaseComObject(session);
        if (currFolder != null)
            Marshal.ReleaseComObject(currFolder);
        if (currExplorer != null)
            Marshal.ReleaseComObject(currExplorer);
    }
}

The code above grabs the name of the rule to run from the combo-box and executes the rule on the currently open folder in the Outlook Explorer, if it finds mails with the words "Order" or "Orders" in their subject lines it then moves them to the Orders folder. It will also search the current folder's sub-folders if the user has checked the "Include Sub-folders" checkbox on the ribbon tab.

It's a good idea to set the first parameter of the Execute() method to True, as this will then display a progress window, indicating to the user that Outlook is busy executing a rule and will stop the user from thinking Outlook is hanging.

A progress window indicating that Outlook is executing the rule

And as easy as that you too can harness the power of Outlook Rules in your Microsoft Outlook add-in!

Thank you for reading! Until next time, keep coding!

Available downloads:

This sample Outlook add-in was developed using Add-in Express for Office and .net:

C# sample Outlook add-in

You may also be interested in:

Post a comment

Have any questions? Ask us right now!