Extending Outlook Rules via Scripting

AID: 420
  • Status: Published

11345 points

  • ByBlueDevilFan
  • TypeGeneral
  • Posted on2009-01-18 at 18:02:57
Awards
  • Community Pick
  • Experts Exchange Approved
Scenario.  Outlook rules are a great way to automate message processing.  Using rules you can organize your messages, forward or reply to messages automatically, display custom message alerts, set reminders, and more.  Unfortunately, rules have two severe limitations.  First, if your mailbox is on an Exchange server, then there is a limit (32K) to the aggregate size of all your rules.  If you reach that limit, then the only way to create another rule is to delete an existing one.  Second, Outlook's built-in rules wizard offers a limited set of conditions and actions.  If you want your rule to key on a condition that isn't offered, or perform and action that isn't in the list, then you are stuck.


Solution.  The solution to both limitations is to employ Outlook's ability to have a rule run a script.  By calling a script your rule can perform almost any action, or at least any task that you can script.  Scripts give you access to all of the commands available in Microsoft's Visual Basic for Applications (VBA) language, which includes interacting with other Microsoft Office applications.  It also provides for making calls to any COM component available to Visual Basic.  Scripting enables you to combine multiple rules into a single rule (e.g. multiple rules that file messages by sender can be combined), create conditions that aren't possible via the rules wizard (e.g. the rule's wizard only supports AND conditions, not OR, and not NOT), and perform actions well beyond those available through the wizard.  


Requirements.  The ability to call a script from a rule is available to Outlook 2002 and later.  Obviously you must be familiar enough with writing VBA code to be able to write the script.  The only other requirement is that Outlook must be running for the rule and script to work.  Rules that call scripts run at the client (i.e. Outlook), not the mail server (i.e. Exchange).  If Outlook is not running, then the rule will not fire and run the code.


1

Creating the Script

   
For a script to be available to Outlook's rules engine it must be properly formatted.  Here's an example of a properly formatted script that can be called from a rule.  The key is the Item As Outlook.MailItem.  That declaration tells the script to accept a lone parameter, the message triggering the script.  Scripts without this declaration cannot be called from a rule.  

    Sub MyRule(Item As Outlook.MailItem)
        'Your custom VBA code goes here'
    End Sub
                                    
1:
2:
3:

Select allOpen in new window



To create a script,

a.  Click Tools > Macro > Visual Basic Editor, or press ALT+F11.
b.  If not already expanded, expand Project1 in the project pane.
c.  If not already expanded, expand Modules in the project pane.
d.  If a module already exists in modules, then select it and skip to step f.
e.  Right-click on Modules and select Insert > Module.  Select the newly created module.
f.  Copy the code in the snippet above and paste it into the right-hand pane of the VB editor.g7.  Change

MyRule
to the name you want to give the script.
g.  Replace
'Your custom VBA code goes here'
with your code.



2

Creating the Rule


a.  Click Tools > Rules and Alerts.
b.  Click the New Rule button.
c.  Select "Start from a blank rule" and click Next.
d.  The first step to creating the rule is to set the condition that triggers the rule.  You have a choice here.  Create a condition, or leave the condition blank in which case the rule will fire for all messages.  The latter is the option to choose if you want the script to control the condition.  For example, if you want to create a single rule that will file messages for multiple senders, then leave the condition blank and write the script to handle multiple senders.  If instead you want to perform an action that isn't available via the wizard for a single sender, then go ahead and set a condition.  Click Next.
e.  Select the "run a script" action.
f.  In the lower panel click "a script" and select the script you created in step 1.
g.  Click Finish.
h.  Make sure the box next to the rule is checked to make it active.



3

Running the Rule


Each time a new message arrives that meets the condition set in the rule, or all messages if no condition was set, the rule fires the script and passes it a copy of the message that triggered the rule.  (Note that rules only work for messages.  They do not work from task requests, meeting requests, receipts (delivery or read), or non-delivery reports.  Although these look like message they are not.)  The script then runs and performs whatever actions you wrote it to take.  You can also run these rules on demand just as you can with normal rules.



Examples.

1.  This example demonstrates how to assign a category to messages based on the sender's name.

Sub CategorizeBySender(Item As Outlook.MailItem)
    Select Case LCase(Item.SenderName)
        Case "bob jones", "sam smith", "jane doe"
            Item.Categories = "Business"
        Case "tom davis", "mary wilson"
            Item.Categories = "Friends"
        Case Else
            Item.Categories = "Unknown"
    End Select
    Item.Save
End Sub
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

Select allOpen in new window



2.  This example demonstrates saving all message attachments to a folder in the file system.

Sub SaveAttachmentsToFolder(Item As Outlook.MailItem)
    Dim objFSO As Object, _
        olkAttachment As Outlook.Attachment, _
        strFolderName As String
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    For Each olkAttachment In Item.Attachments
        'Change the root folder path on the following line as needed'
        strFolderName = "C:\RootFolder\" & objFSO.GetExtensionName(olkAttachment.FILENAME)
        If Not objFSO.FolderExists(strFolderName) Then
            objFSO.CreateFolder strFolderName
        End If
        olkAttachment.SaveAsFile strFolderName & "\" & olkAttachment.FILENAME
    Next
    Set objFSO = Nothing
    Set olkAttachment = Nothing
End Sub
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:

Select allOpen in new window



3.  This example demonstrates creating a contact for the sender of all messages you receive.

Sub AutoCreateContact(Item As Outlook.MailItem)
    Dim olkContacts As Object, _
        olkContact As ContactItem, _
        strAddress As String, _
        strName As String
    Set olkContacts = Application.Session.GetDefaultFolder(olFolderContacts)
    strName = Item.SenderName
    strAddress = Item.SenderEmailAddress
    Set olkContact = olkContacts.Items.Find("[FullName] = " & Chr(34) & strName & Chr(34))
    If TypeName(olkContact) = "Nothing" Then
        If Item.SenderEmailType = "SMTP" Then
            Set olkContact = Application.CreateItem(olContactItem)
            With olkContact
                .Email1Address = strAddress
                .FullName = strName
                'Change or remove the following line as desired'
                .Body = "Record created automatically on " & Date & " at " & Time & " by BlueDevilFan's script."
                'Create a similar IF ... END IF sequence for each category you want to add'
                If InStr(1, Item.Body, "TechRepublic") Then
                    .Categories = AddCategory(.Categories, "TechRepublic")
                End If
                .Save
            End With
        End If
    End If
    Set olkContact = Nothing
    Set olkContacts = Nothing
End Sub
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:

Select allOpen in new window

Asked On
2009-01-18 at 18:02:57ID420
Tags

Microsoft

,

Office

,

Outlook

,

VBA

,

Macro

,

Rules

Topic

Outlook Groupware Software

Views
14524

Comments

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top Outlook Experts

  1. apache09

    663,644

    Sage

    2,168 points yesterday

    Profile
    Rank: Genius
  2. alanhardisty

    170,946

    Guru

    0 points yesterday

    Profile
    Rank: Genius
  3. demazter

    131,854

    Master

    0 points yesterday

    Profile
    Rank: Genius
  4. chris_bottomley

    109,375

    Master

    2,800 points yesterday

    Profile
    Rank: Genius
  5. thinkpads_user

    95,624

    Master

    750 points yesterday

    Profile
    Rank: Genius
  6. Rajkumar-MCITP

    89,780

    Master

    0 points yesterday

    Profile
    Rank: Guru
  7. l33tf0b

    83,091

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  8. BlueDevilFan

    73,191

    Master

    50 points yesterday

    Profile
    Rank: Savant
  9. jjmck

    66,336

    Master

    0 points yesterday

    Profile
    Rank: Genius
  10. Neilsr

    61,466

    Master

    0 points yesterday

    Profile
    Rank: Genius
  11. amitkulshrestha

    61,377

    Master

    0 points yesterday

    Profile
    Rank: Genius
  12. jcimarron

    49,232

    0 points yesterday

    Profile
    Rank: Genius
  13. ve3ofa

    46,002

    0 points yesterday

    Profile
    Rank: Genius
  14. dlmille

    45,200

    0 points yesterday

    Profile
    Rank: Genius
  15. akicute555

    44,979

    10 points yesterday

    Profile
    Rank: Wizard
  16. Anuroopsundd

    44,529

    0 points yesterday

    Profile
    Rank: Sage
  17. HendrikWiese

    40,896

    2,000 points yesterday

    Profile
    Rank: Sage
  18. Exchange_Geek

    37,449

    0 points yesterday

    Profile
    Rank: Sage
  19. jordannet

    36,757

    0 points yesterday

    Profile
    Rank: Wizard
  20. acbrown2010

    34,652

    0 points yesterday

    Profile
    Rank: Genius
  21. diverseit

    34,600

    0 points yesterday

    Profile
    Rank: Guru
  22. WORKS2011

    32,775

    0 points yesterday

    Profile
    Rank: Guru
  23. e_aravind

    31,941

    0 points yesterday

    Profile
    Rank: Genius
  24. JBlond

    31,700

    0 points yesterday

    Profile
    Rank: Sage
  25. limjianan

    30,910

    0 points yesterday

    Profile
    Rank: Genius

Hall Of Fame