Link to home
Start Free TrialLog in
Avatar of Jerry L
Jerry LFlag for United States of America

asked on

Outlook: Custom Script Needed to Filter Email Messages in Place of Rules Wizard

Script needed to replace Outlook Rules Wizard

--------------------------------------
       Description of Problem
---------------------------------------
I would like to obtain a script that performs the following actions :

I've created a custom rule with the Rules Wizard that has a list of entries in it.  The rule is that, when these phrases appear in the email header, the message should be moved to another folder.  

         Apply this rule after the message arrives
         with __________ in the message header
       
When you click on the area of text after "with", the entries appear in a scrollable dialog box with a text box which allows you to add or remove items.  When this list gets above 100 items, however, it gets unmanageable and difficult to see what entries are invalid or duplicates.

If I had a script to replace the Rules Wizard, I could edit those entries all I want.  


-------------------------------------------
              My Question
-------------------------------------------
Can someone please help me write this script and explain what tools I need to edit and run it?  I've never worked with MS Office scripts before, except in Excel.  I know some C/C++ but my Visual Basic is not good and I don't have a lot of time to learn it.

Here is a link to the Microsoft Tech Net that outlines how to write a script for Outlook.  It should be helpful in getting started:

http://www.microsoft.com/technet/scriptcenter/resources/officetips/aug05/tips0818.mspx
SOLUTION
Avatar of Brian Mulder
Brian Mulder
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of David Lee
WizeOwl,
What do you mean by "message header"?  Are you talking about the message subject, or the internet header?  I'm asking because there is a separate option for specific words in the subject.

bruintje,
Nice script.  Would each word check be faster if you used the Dictionary object instead of an array?  
you could be right on that message header BlueDevilFan, that is something different :-)

about the dictionary object i'm not sure, it would seem faster because you can directly search for an item but it would take a look if you are looking for a part of the header in the dictionary collection or not?
Avatar of Jerry L

ASKER

I haven't had a chance to try that script yet, bruintje, but regarding headers, BlueDevilFan, when I right click on a message and select "Options" it shows the contents of "Internet Headers".

I assume this is the line that looks at the "Subject" contents for string match -

      If InStr(1, Item.Subject, strCheckList(i)) > 0

So now I need the variable to replace "Item.Subject" to "Item.Header" .

My replies may not be prompt since I am busy with another project during this time but I appreciate your assistance with this issue, and will try this solution by next week.
> So now I need the variable to replace "Item.Subject" to "Item.Header" .
There is no "Header" property in the Outlook object model.  Reading the internet header requires using MAPI objects instead.  Something like this:

Function GetInternetHeaders(olkItem As Outlook.MailItem) As String
    'Set the error handler to allow us to handle errors in code
    On Error Resume Next

    'Declare a constant
    Const CdoPR_TRANSPORT_MESSAGE_HEADERS = &H7D001E

    'Declare a few variables
    Dim mapSession As Object, _
        mapMessage As Object, _
        mapFields As Object, _
        strHeader As String

    'Create a CDO session and login to it using the existing Outlook session
    Set mapSession = CreateObject("MAPI.Session")
    mapSession.Logon , , False, False, 0

    'Get the selected message's ID
    Set mapMessage = mapSession.GetMessage(olkItem.EntryID, olkItem.Parent.StoreID)

    'Get message fields
    Set mapFields = mapMessage.Fields

    'Get the Internet header
    Err.Clear
    strHeader = mapFields.Item(CdoPR_TRANSPORT_MESSAGE_HEADERS).Value
    If Err.Number = 0 Then
        GetInternetHeaders = strHeader
    Else
        GetInternetHeaders = "Unable to retrieve internet header information."
    End If

    'Logout of the CDO sesison
    mapSession.Logoff

    'Clean up
    Set mapSession = Nothing
    Set mapMessage = Nothing
    Set mapFields = Nothing
End Function

This function returns the internet header for the message passed to it.  If there is no header, which will be the case on internal messages, then it returns the message "Unable to retrieve internet header information."  This function does require that the CDO libraries be on the comptuer it's run on.  You may also be surprised at the information returned.  I recommend running it against a couple of messages first to make sure it's returning the information you expected.

bruintje,

Yes, it does take a look either way.  I was just wondering if each query would process faster since there'd be no need to itterate through an n-length array each time.  Not knowing exactly how the Dictionary object works behind the scenes it might just be itterating its own array.  But I'm hoping it uses a hash of some sort and is able to check for the existence of a value without having to do that.  
Avatar of Jerry L

ASKER

I appreciate the hard work you have put into this problem and will reward with max points.  If a question arises that needs to be given extra points, I will submit that separately as well.  If anything is unclear, let me know and I'll rephrase.

Meanwhile, I have some issues and questions before I can use either of these scripts.

bruintje wrote:  Script 1

     (1) - in Outlook open the VBA Editor with ALT+F11
     (2) - look for the ThisOutlookSession object in the upper left pane
     (3) - paste this code in the right pane, which is the code pane


My Results
--------------------
(1) Done.
(2) Done.
(3) Done.
 -   I created a file, C:\SubjectEntryList.text, and entered the string of the subject of a message already in the Inbox.  You said to put words in this file, I assume it can be one text string per line, which includes spaces between words?  
      subject one
      subject 2 that has several words
      ... etc.

-    I created a subfolder of Inbox called EE (just to test the code as-is, I know I can change it later).


Question:
---------------
1a) I'm not exactly sure how to run Script 1.  I tried Alt F8 which brought up the Run Macro dialog box, but it was empty, no macros at all.  Does it run automatically and only sort messages that haven't been received yet?  This is like the action in the Rules Wizard that says to act on messages received through the account _______ and move to folder ________.  

  b) Is there a way to make it act on messages already in the folder?  

2) I'm not sure what to do with Script 2, the one handling InternetHeaders.  Is that meant to replace Script 1 in the "ThisOutlookSession" code?  Can there be only one Script there at a time?

3) Is it possible to create several "Rules" as scripts and run them in sequence and/or manually?


Notes:
---------------
- From VB Editor, 'View -> Project Explorer' allows me to see module 1 and 2 in the Left Side Box next to the code.  

- After adding the two modules, I can now see "ThisOutlookSession" Listed under  Project 1 (vbaProject.OTM) - I placed the code there after having placed it in a module the first time.
Hi again

the first script works based on the email subject

1a.  Does it run automatically and only sort messages that haven't been received yet?
Yes, it does run on each new mail item

1b. Is there a way to make it act on messages already in the folder
Yes, have to post that a bit later

2. The second script from BlueDevilFan acts on the email headers (different from subject)
No, you can run several scripts at one time, but they will act in sequence

My question is what do you need :)
Do you need to check on email headers (containing routing info etc...) or email subjects (the text you see as the headline of the message)

if we know that the script can be changed also to run for messages already in the mailbox
Avatar of Jerry L

ASKER

> What do you need ...

The main request in this PAQ is as follows:
--------------------------------------------------------
   - I need a script that will perform and replace a rule in the Rules Wizard.
   - That rule will perform an action based on the content found in the Internet Headers.
   - Required actions will be to 1) move the message to a specified folder, or 2) to delete it.  One rule (script) will perform either 1) or 2), obviously can't do both.

   1)  "When a message arrives with ______ (string list #1) in the Header, move it to the ______ folder."
or,
   2)  "When a message arrives with ______ (string list #2) in the Header, delete it."


That will satisfy this PAQ.

The only reason I'm even requesting this is because the Rules Wizard is not performing properly and I need to override it with my own scripts.

--------------------------------------------------------
Problem with Rules Wizard #1

When I include the instruction: "and stop processing more rules" many 'good' messages end up in junk folder.  When I omit that instruction, many duplicates end up in my sub-folders.

I'd like to find another script that will overcome this problem.  That will require having the option to sort on one of two criteria:
   1)  "When a message arrives with ______ (string list) in the Subject, move it to the ______ folder."
   2)  "When a message arrives from ______ account, move it to the ______ folder."
  ** There is no problem with this function (#2) in the Rules Wizard and therefore it should not need to be duplicated with a script, but might be good to have in case I eliminate Rules Wizard completely.

--------------------------------------------------------
Problem with Rules Wizard #2

When in the Rules Wizard, you can select the option, "Run Rules Now".  I would like to simulate that function.  That's the one that runs on messages already in a folder and has an option (check box) to perform the action in the sub-folders or not.

The main problem with "Run Rules Now" is that you have to select each check box one-at-a-time.  What a pain!  I've got over 25 rules to run.  It would be nice to be able to drag your mouse to select multiple rules, or use the <Shift> or <Ctrl> selection options like when you select multiple, sequential or non-sequential messages or files to open in Outlook Inbox or Windows Explorer (file manager).

And the only reason I need to Run Rules Now is because the rules didn't work properly the first time!

--------------------------------------------------------
Rather than ask for all of this in one post, I believe I should create another post (or multiple others) in order to award points separately since more work will be involved.
Avatar of Jerry L

ASKER

- Bump -

You asked me "What do you need" and I responded, so I thought I was going to receive an update...
Hi, WizeOwl.

Give me an example or two of text you'd expect to find in the intenet header and the action you'd take for each.
Avatar of Jerry L

ASKER

I apologize for the delay. I would like to fully replace the Rules Wizard with custom scripts.   I don't use all features of the rules so I don't need a full replacement in that sense, but only the functions that I use.

- I would like to allow these scripts to run automatically every time I retrieve email.

- I need to be able to turn them on or off selectively and run in batch mode (one or more at a time).

- I would also like to be able to run these scripts manually (and selectively, batch mode, one or more at a time) from a given folder that applies only to that folder [provide a switch: sub-folders "on" OR "off"]

Here is a list of functions that I am currently using:

   - Delete email message with a given phrase (or list of phrases) in the Subject.
   - Delete email with given phrase (or list of phrases) in the header.
   - Delete email with given phrase (or list of phrases) in the Subject OR Header.

   - Delete email sent TO a given Recipient (or list of recipients).
   - Delete email sent FROM a given Sender (or list of senders).

   - Move email with a given phrase (or list of phrases) in the Subject to another folder.
   - Move email with given phrase (or list of phrases) in the Header to another folder.
   - Move email with a given phrase (or list of phrases) in the Subject OR Header to another folder.

   - Move email sent TO a given Recipient (or list of recipients) to another folder.
   - Move email sent FROM a given Sender (or list of senders) to another folder.

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial