51

Is it possible to create rules in Outlook 2007 based on a regex string?

I'm trying to add a filter for messages containing a string such as: 4000-10, a four digit number followed by a dash and then a two digit number, which can be anything from 0000-00 to 9999-99.

I was using this as a regex: \b[0-9]{4}\-[0-9]{2}\b but the filter isn't working. I've tried a few other modifications as well with no luck. I wasn't able to find anything concrete online about whether Outlook even supports entering regexes into a rule, though, so I figured I would ask here in case I'm wasting my time.

EDIT: Thanks to Chris's comment below, I was able to implement this filter via a macro. I thought I would share my code below in case it is able to help anyone else:

Sub JobNumberFilter(Message As Outlook.MailItem)
    Dim MatchesSubject, MatchesBody
    Dim RegEx As New RegExp

    'e.g. 1000-10'
    RegEx.Pattern = "([0-9]{4}-[0-9]{2})"

    'Check for pattern in subject and body'
    If (RegEx.Test(Message.Subject) Or RegEx.Test(Message.Body)) Then
        Set MatchesSubject = RegEx.Execute(Message.Subject)
        Set MatchesBody = RegEx.Execute(Message.Body)
        If Not (MatchesSubject Is Nothing And MatchesBody Is Nothing) Then
            'Assign "Job Number" category'
            Message.Categories = "Job Number"
            Message.Save
        End If
    End If
End Sub
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274
  • 1
    Is this really programming related? I mean, you do not ask if the regex is correct, only if outlook supports regexes – Oskar Kjellin Oct 05 '10 at 16:12
  • 1
    I actually meant it as both questions. I haven't used regexes much, so I was uncertain to that as well. In the same aspect though, if Outlook doesn't even support regexes, the point is moot, so that was kinda where I was going with it. – Kevin Coppock Oct 05 '10 at 16:15
  • 1
    I don't think it matters, this seems to match it as well = "[0-9]{4}-[0-9]{2}" – Oskar Kjellin Oct 05 '10 at 16:21
  • 1
    Ah okay, I see. Maybe it only matters within `[]` braces. Thanks! – Kevin Coppock Oct 05 '10 at 16:22
  • 2
    @Will I don't think individuals should ever close questions. There's a lot of code (ergo programming) involved in all aswers, so it's a programming question. – Tomáš Zato Oct 14 '15 at 14:08
  • @TomášZato mods would disagree. I can't see the flags on this question anymore, so I can't be 100% sure the situation surrounding its closure. I'll flag for clarification on that. The question isn't all that good, being either a yes/no question (e.g., "yes, you can do that" isn't a helpful answer) or "give me teh codez". Closure doesn't affect anything here negatively, and might have been done to prevent this from being used as an example to allow other, worse questions to be asked. Everything here looks okay now, so I'll cast a vote to reopen. –  Oct 14 '15 at 16:03
  • @TomášZato side note, read the first two comments here, which might suggest why the original question was closed. The selected answer brings this question firmly on-topic, but without it this might have appeared to be better suited for [su], where questions about creating filters in outlook belong. –  Oct 14 '15 at 16:07

2 Answers2

55

I do not know if a regex can be used directly in a rule, but you can have a rule trigger a script and the script can use regexes. I hate Outlook.

First, you have to open the script editor via Tools - Macro - Open Visual Basic Editor (Alt-F11 is the shortcut).

The editor will open. It should contain a project outline in a small panel in the top-left corner. The project will be listed as VBAProject.OTM. Expand this item to reveal Microsoft Office Outlook Objects. Expand that to reveal ThisOutlookSession. Double-click ThisOutlookSession to open the code editing pane (which will probably be blank).

Next select Tools menu | References and enable the RegExp references called something like "Microsoft VBScript Regular Expressions 5.5"

You can now create a subroutine to perform your filtering action. Note that a subroutine called by a rule must have a single parameter of type Outlook.MailItem. For example:

' note that Stack Overflow's syntax highlighting doesn't understand VBScript's
' comment character (the single quote) - it treats it as a string delimiter.  To
' make the code appear correctly, each comment must be closed with another single
' quote so that the syntax highlighter will stop coloring everything as a string.'

Public Enum Actions
    ACT_DELIVER = 0
    ACT_DELETE = 1
    ACT_QUARANTINE = 2
End Enum

Sub MyNiftyFilter(Item As Outlook.MailItem)
    Dim Matches, Match
    Dim RegEx As New RegExp
    RegEx.IgnoreCase = True

    ' assume mail is good'
    Dim Message As String: Message = ""
    Dim Action As Actions: Action = ACT_DELIVER

    ' SPAM TEST: Illegal word in subject'
    RegEx.Pattern = "(v\|agra|erection|penis|boner|pharmacy|painkiller|vicodin|valium|adderol|sex med|pills|pilules|viagra|cialis|levitra|rolex|diploma)"
    If Action = ACT_DELIVER Then
        If RegEx.Test(Item.Subject) Then
            Action = ACT_QUARANTINE
            Set Matches = RegEx.Execute(Item.Subject)
            Message = "SPAM: Subject contains restricted word(s): " & JoinMatches(Matches, ",")
        End If
    End If

    ' other tests'

    Select Case Action
        Case Actions.ACT_QUARANTINE
            Dim ns As Outlook.NameSpace
            Set ns = Application.GetNamespace("MAPI")

            Dim junk As Outlook.Folder
            Set junk = ns.GetDefaultFolder(olFolderJunk)

            Item.Subject = "SPAM: " & Item.Subject
            If Item.BodyFormat = olFormatHTML Then
                Item.HTMLBody = "<h2>" & Message & "</h2>" & Item.HTMLBody
            Else
                Item.Body = Message & vbCrLf & vbCrLf & Item.Body
            End If

            Item.Save
            Item.Move junk

        Case Actions.ACT_DELETE
            ' similar to above, but grab Deleted Items folder as destination of move'

        Case Actions.ACT_DELIVER
            ' do nothing'
    End Select
End Sub


Private Function JoinMatches(Matches, Delimeter)
    Dim RVal: RVal = ""

    For Each Match In Matches
        If Len(RVal) <> 0 Then
            RVal = RVal & ", " & Match.Value
        Else
            RVal = RVal & Match.Value
        End If
    Next

    JoinMatches = RVal
End Function

Next, you have to create a rule (Tools - Rules and Alerts) to trigger this script. Click the New Rule button on the dialog to launch the wizard. Select a template for the rule. Choose the "Check messages when they arrive" template from the "Start from a blank rule" category. Click Next.

Choose the "On this machine only" condition (intuitive isn't it?) and click next.

Choose the "run a script" option. At the bottom of the wizard where it shows your new rule, it should read:

Apply this rule after the message arrives
on this machine only
run a script

The phrase "a script" is a clickable link. Click it and Outlook will display a dialog that should list the subroutine you created earlier. Select your subroutine and click the OK button.

You can click Next to add exceptions to the rule or click Finish if you have no exceptions.

Now, as though that process was not convoluted enough, this rule will deactivate every time you stop and restart Outlook unless you sign the script with a code signing key.

If you don't already have a code signing key, you can create one with OpenSSL.

Did I mention that I hate Outlook?

lessthanideal
  • 1,084
  • 13
  • 14
Chris Judge
  • 1,952
  • 1
  • 13
  • 10
  • Wow. Yeah, I can understand your pain. I've done some light programming in PowerPoint (horrible nightmare as well) and it's horrendous. Thank you very much for the very detailed answer! I'll do some work on this when I get some free time and see what I can do. Again, thank you! – Kevin Coppock Oct 05 '10 at 17:46
  • Just to add to this, I've found there's an alternate, easier way of signing a macro: using a self-signed certificate. http://msdn.microsoft.com/en-us/library/aa155754(office.10).aspx#oldigitalsignature_sign You can create one through an optionally installed part of Office called Digital Certificate for VBA Projects. – Kevin Coppock Oct 12 '10 at 13:45
  • 1
    +1 (i wish i could +1000!) for the `Enum`. I think I need to go back and make every Macro I've ever written about a million times more readable! Thanks! – airstrike Sep 14 '16 at 14:28
  • it's work in subject but how to filter html body? I've got something like . I fould like to filter this – JanuszO Sep 06 '18 at 12:06
17

Microsoft Outlook does not support regular expressions. You can perform wildcard searches, although for some inexplicable reason the wildcard character is %, not *.

Ether
  • 53,118
  • 13
  • 86
  • 159
  • 1
    Thanks Ether. That is bizarre that they would change the wildcard character. – Kevin Coppock Oct 05 '10 at 16:46
  • 2
    This KB article isn't about the rules wizard per se, rather an add-on for CRM. If you parse the article you'll see that it makes complete sense as to why the % sign is used in this context. It's because it's a SQL query where the wildcard character is indeed a % – noonand Aug 01 '12 at 08:43
  • MS 2013 does support a percent character when searching email subjects and bodies (at least) from the main Search ribbon looking at the inbox. But if you create a "Search Folder" (virtual folder whose contents is the results of various search conditions), the search conditions in the "Search Folders" do *not* support the percent wildcard. Way to go Microsoft >;) – Ben Slade Oct 29 '15 at 17:58
  • No wonder all of my wildcard searches have never worked. Thanks! +1 – airstrike Sep 14 '16 at 14:29
  • Your link is dead – Alexxus Sep 11 '18 at 10:06