使用python从发件人电子邮件地址在Outlook中创建规则

时间:2019-07-11 01:02:50

标签: python email outlook rules

我正在尝试创建规则以将电子邮件从一长串发件人移动到特定文件夹。例如,如果我收到来自john@email.com的电子邮件,则希望将其从“收件箱”移至“ workstuff \ John”(john是worktuff的子文件夹)。

我正在使用comtypes.clients和python来完成此操作,因为我发现了类似的帖子(Setting a property using win32com),其中答案之一是在python中使用comtypes.clients。 我还使用https://docs.microsoft.com/en-us/office/vba/outlook/how-to/rules/create-a-rule-to-move-specific-e-mails-to-a-folder作为指导。

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()

我已经能够创建规则,该规则将显示在Outlook中。但是规则缺少“来自”部分。基本上说:

”消息到达后应用此规则 将其移至john文件夹“

我希望规则是:

”消息到达后应用此规则 从john@email.com 将其移至john文件夹“

1 个答案:

答案 0 :(得分:1)

您的帖子中提到的article包含以下用于处理From部分的代码:

'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 

代码应如下所示:

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()