1

I am trying to create rules to move emails from a long list of senders to specific folders. For example, if I receive an email from john@email.com, I want it to be moved from "Inbox" to "workstuff\John" (john is a subfolder of workstuff).

I'm using comtypes.clients and python to do this because I found a similar post ( Setting a property using win32com ), in which one of the answers uses comtypes.clients in python. I am also using https://learn.microsoft.com/en-us/office/vba/outlook/how-to/rules/create-a-rule-to-move-specific-e-mails-to-a-folder as a guideline.

import comtypes.client

o = comtypes.client.CreateObject("Outlook.Application")
rules = o.Session.DefaultStore.GetRules()
rule = rules.Create("Test", 0)
condition = rule.Conditions
condition.From.Recipients.Add(str("fabracht"))
condition.From.Recipients.ResolveAll

#.From.Recipients("fabracht@gmail.com")
condition.Enabled = True
root_folder = o.GetNamespace('MAPI').Folders.Item(1)
dest_folder = root_folder.Folders["Evergreen1"].Folders["Chemistry"]

move = rule.Actions.MoveToFolder
move.__MoveOrCopyRuleAction__com__set_Enabled(True)
move.__MoveOrCopyRuleAction__com__set_Folder(dest_folder)

rules.Save()

I've been able to create the rule, which shows up in outlook. But the rule is missing the "from" part. Basically it says:

" Apply this rule after the message arrives Move it to the john folder "

I expected the rule to be:

" Apply this rule after the message arrives From john@email.com Move it to the john folder "

Fabrex
  • 162
  • 9

1 Answers1

1

The article mentioned in your post contains the following code for dealing with the From part:

'Specify the condition in a ToOrFromRuleCondition object 
'Condition is if the message is from "Eugene Astafiev" 
Set oFromCondition = oRule.Conditions.From 
With oFromCondition 
    .Enabled = True 
    .Recipients.Add ("Eugene Astafiev") 
    .Recipients.ResolveAll 
End With 

The code should look like the following:

import comtypes.client

o = comtypes.client.CreateObject("Outlook.Application")
rules = o.Session.DefaultStore.GetRules()
rule = rules.Create("Test", 0)
condition = rule.Conditions
condition.From.Recipients.Add(str("fabracht"))
condition.From.Recipients.ResolveAll

oFromCondition = oRule.Conditions.From 
oFromCondition.Enabled = True 
oFromCondition.Recipients.Add("john@email.com") 
oFromCondition.Recipients.ResolveAll 

#.From.Recipients("fabracht@gmail.com")
condition.Enabled = True
root_folder = o.GetNamespace('MAPI').Folders.Item(1)
dest_folder = root_folder.Folders["Evergreen1"].Folders["Chemistry"]

move = rule.Actions.MoveToFolder
move.__MoveOrCopyRuleAction__com__set_Enabled(True)
move.__MoveOrCopyRuleAction__com__set_Folder(dest_folder)

rules.Save()

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45