创建将特定电子邮件移动到文件夹的规则
本主题演示 Visual Basic for Applications (VBA) 中的代码示例,该示例使用 Rules 对象模型创建规则。 代码示例使用 RuleAction 和 RuleCondition 对象指定将邮件从特定发件人移动到特定文件夹的规则,除非邮件主题中包含某些术语。 请注意,该代码示例假设在“收件箱”下面已存在一个名为“Dan”的文件夹。
下面说明了用于创建该规则的步骤:
指定目标文件夹
oMoveTarget
以移动由条件和异常条件确定的特定邮件。 该目标文件夹为"收件箱"下面一个名为"Dan"的子文件夹,并且假设该子文件夹已经存在。使用 Store.GetRules 获得当前会话中所有规则的集合。
利用上一步返回的 Rules 集合,使用 Rules.Create 添加一条新规则。 该新规则指定在接收邮件时的一些操作,因此其类型为 olRuleReceive。
利用上一步返回的 Rule 对象,使用 RuleConditions.From 属性获取一个 ToOrFromRuleCondition 对象
oFromCondition
。oFromCondition
指定该规则的条件:当邮件来自Dan Wilson
时。利用同一个 Rule 对象,使用 RuleActions.MoveToFolder 属性获取一个 MoveOrCopyRuleAction 对象
oMoveRuleAction
。oMoveRuleAction
指定该规则的操作:将邮件移到目标文件夹"Dan"。利用同一个 Rule 对象,使用 RuleConditions.Subject 属性获取一个 TextRuleCondition 对象
oExceptSubject
。oExceptSubject
指定异常条件:如果主题包含术语“fun”或“chat”,则不要应用规则将邮件移动到文件夹“Dan”。使用 Rules.Save 将该新规则与当前存储区的其余规则一起保存起来。
Sub CreateRule()
Dim colRules As Outlook.Rules
Dim oRule As Outlook.Rule
Dim colRuleActions As Outlook.RuleActions
Dim oMoveRuleAction As Outlook.MoveOrCopyRuleAction
Dim oFromCondition As Outlook.ToOrFromRuleCondition
Dim oExceptSubject As Outlook.TextRuleCondition
Dim oInbox As Outlook.Folder
Dim oMoveTarget As Outlook.Folder
'Specify target folder for rule move action
Set oInbox = Application.Session.GetDefaultFolder(olFolderInbox)
'Assume that target folder already exists
Set oMoveTarget = oInbox.Folders("Dan")
'Get Rules from Session.DefaultStore object
Set colRules = Application.Session.DefaultStore.GetRules()
'Create the rule by adding a Receive Rule to Rules collection
Set oRule = colRules.Create("Dan's rule", olRuleReceive)
'Specify the condition in a ToOrFromRuleCondition object
'Condition is if the message is from "Dan Wilson"
Set oFromCondition = oRule.Conditions.From
With oFromCondition
.Enabled = True
.Recipients.Add ("Dan Wilson")
.Recipients.ResolveAll
End With
'Specify the action in a MoveOrCopyRuleAction object
'Action is to move the message to the target folder
Set oMoveRuleAction = oRule.Actions.MoveToFolder
With oMoveRuleAction
.Enabled = True
.Folder = oMoveTarget
End With
'Specify the exception condition for the subject in a TextRuleCondition object
'Exception condition is if the subject contains "fun" or "chat"
Set oExceptSubject = _
oRule.Exceptions.Subject
With oExceptSubject
.Enabled = True
.Text = Array("fun", "chat")
End With
'Update the server and display progress dialog
colRules.Save
End Sub
支持和反馈
有关于 Office VBA 或本文档的疑问或反馈? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。