Python Script to Turn Outlook E-Mail Rules on and Off

1k views Asked by At

I'm trying to write a Python script/program to turn off E-Mail Rules I've created in Outlook 2010.

Through VBA, I've managed to write a function that will turn an array of rule names on and off based on a passed in boolean.

Function toggleRules(ruleNames() As String, tf As Boolean) As Boolean
Dim olRules As Outlook.Rules
Dim olRule As Outlook.Rule
Dim blnExecute As Boolean

For Each Rule In ruleNames()
  Set olRules = Application.Session.DefaultStore.GetRules
  Set olRule = olRules.Item(Rule)

  olRule.Enabled = tf

  If blnExecute Then olRule.Execute ShowProgress:=True
    olRules.Save

  Set olRules = Nothing
  Set olRule = Nothing
Next Rule

End Function

This works, and will turn on/off the rules I send it by name with other VBA functions. If you're curious, currently when a task reminder with a certain subject fires it will call this function.

I'd like to accomplish this via python so I can trigger it with more sophistication than just reminder timers, and just general cause I'd prefer to do it that way. It seems that it can be done with the pywin32 extension:

http://sourceforge.net/projects/pywin32/

However I'm having a hard time trying to get to the Rules interface. I can get to the Outlook Application and namespace, but can't seem to figure out where to go from here.

import win32com.client
x = win32com.client.gencache.EnsureDispatch("Outlook.Application")
y = x.GetNamespace("MAPI")

Ultimately I'd like to basically have the same function, that given a list of names and a bool, have it toggle those rules in outlook.

Thanks.

2

There are 2 answers

0
Eugene Astafiev On BEST ANSWER

The Outlook object model is common for all kind of applications (VBA, COM add-ins, automation and etc.). After you got an instance of the Namespace class you can get the default store (or iterate over all stores in the profiles).

The DefaultStore property of the Namespace class returns a Store object representing the default Store for the profile.

The Stores property of the Namespace class returns a Stores collection object that represents all the Store objects in the current profile.

Finally, the Store class provides the GetRules method which returns a Rules collection object that contains the Rule objects defined for the current session.

0
user166729 On

Thanks for the guidance, I was able to figure it out!

For those interested, here's a basic outline the long way to get there and disable the rule:

import win32com.client
x = win32com.client.gencache.EnsureDispatch("Outlook.Application")
y = x.GetNamespace("MAPI")
z = y.DefaultStore
a = z.GetRules()
b = a.Item("My Rule Name")
b.Enabled = False
a.Save()

Thanks again Eugene Astafiev