Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Adding a sender's address to an Outlook Rule via VB for Applications

Posted on 2015-01-06
9
Medium Priority
?
280 Views
Last Modified: 2015-01-18
Hi.
The boss wants a button in Outlook to add a sender to a rule.  I am testing this on my PC, so in my example I have a rule called "Photography".  That rule moves emails (upon receipt) to a folder called "Stuff".  There are a handful of email addresses already in this rule, so that email from "news@OnOne.com" will be put into the "Stuff" folder.  The rule works fine.

Now, I need to be able to highlight an email in the inbox, click a button, and have the sender's address added to the list of senders in the rule.  So, if I highlight an email from "bob@photo.com" and click my button, he gets added to the rule.

I'm pretty close, I think, with close I've cobbled together from other solutions.
It seems to add the address to the rule, but I get an error when I try to .Save the rule.  See attached image.

Any suggestions?
Thanks


Sub AddToRule_RETAIL()
    Dim bFound As Boolean
    
    bFound = False
    
    Dim colRules As Outlook.Rules
    Dim oRule As Outlook.Rule
    
    Set colRules = Application.Session.DefaultStore.GetRules()
    
    '--- find the rule object ...
    For Each ruleItem In colRules
        Debug.Print ruleItem.Name
        If ruleItem.Name = "Photography" Then
            Set oRule = ruleItem
            bFound = True
            Exit For
       End If
    Next
    
    If bFound = False Then
        MsgBox "Rule 'Photography' not found!"
        Exit Sub
    End If
    
    '--- get selected item email address
'    Dim Session As Outlook.NameSpace
    Dim currentExplorer As Explorer
    Dim Selection As Selection
    Dim currentItem As Object
    Dim currentMail As MailItem
    Dim currentSenderAddress As String
    
    
    Set currentExplorer = Application.ActiveExplorer
    Set Selection = currentExplorer.Selection
    
    '--- for all items do...
    For Each currentItem In Selection
        If currentItem.Class = olMail Then
            Set currentMail = currentItem
            
            currentSenderAddress = currentMail.SenderEmailAddress
            
            '-- add it ...
            Set oFromCondition = oRule.Conditions.From
            With oFromCondition
                 .Recipients.Add (currentSenderAddress)
            End With
            
            '-- Update the server and display progress dialog
            colRules.Save
        End If
    Next

End Sub

Open in new window

Capture.JPG
0
Comment
Question by:Rob Rudloff
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
9 Comments
 
LVL 76

Accepted Solution

by:
David Lee earned 2000 total points
ID: 40534832
Hi, RobRud.

This should do it.

Sub AddToRule()
    Dim olkCol As Outlook.Rules, _
        olkRul As Outlook.Rule, _
        olkCnd As Outlook.ToOrFromRuleCondition, _
        olkMsg As Outlook.MailItem
    Set olkCol = Session.DefaultStore.GetRules
    Set olkRul = olkCol.Item("Photography")
    For Each olkMsg In Application.ActiveExplorer.Selection
        If TypeName(olkRul) <> "Nothing" Then
            Set olkCnd = olkRul.Conditions.From
            olkCnd.Recipients.Add olkMsg.SenderEmailAddress
            olkCnd.Recipients.ResolveAll
            olkCol.Save False
        End If
    Next
    Set olkMsg = Nothing
    Set olkCnd = Nothing
    Set olkRul = Nothing
End Sub

Open in new window

0
 

Author Comment

by:Rob Rudloff
ID: 40536968
Thanks BDF:
That executes without error, hitting each line as expected.
However, the email address doesn't get added to the rule  -- I highlighted an email from tapaz.com and it did see it in the .SenderEmailAddress property, but you can see in the attached screen capture that only one sender is in the rule still.

I thought perhaps it had something to do with Exchange -- I noticed my test "Photography" rule is not "client-only", but I have a few rules that are.   I switched the code to use the "Jobs" rule, but the sender's email address didn't show up in there either.

Any ideas?
Thanks!
Capture.2JPG.JPG
0
 
LVL 76

Assisted Solution

by:David Lee
David Lee earned 2000 total points
ID: 40537539
The code isn't working because the rule you're using is different rule than what I was expecting.  Your rule is using the "With specific words in the sender's address" condition while I was thinking that it was using the "from people or public group" condition.  The former is used to process messages from entire domains whereas the latter is used to process messages from specific senders.  I can modify the code to handle that type of rule.  Before doing that, are you sure that you want to stick to that type of rule (i.e. specific words in the sender's address)?
0
Office 365 Training for IT Pros

Learn how to provision tenants, synchronize on-premise Active Directory, implement Single Sign-On, customize Office deployment, and protect your organization with eDiscovery and DLP policies.  Only from Platform Scholar.

 

Author Comment

by:Rob Rudloff
ID: 40538339
BlueDevilFan:
  I know there's a difference, but I don't know what it is
...  If I use "from people", does that mean that those people need to exist as a Contact in Outlook?   The rule should work for emails from everyone, so I reckon I want to use "specific words in the sender's address" ?

Thanks!
0
 
LVL 76

Assisted Solution

by:David Lee
David Lee earned 2000 total points
ID: 40538594
The difference is primarily a matter of scope.  A rule that uses "With specific words" is typically used to perform and action on all messages from an entire domain.  For example, move all messages with "Amazon" in the address to a specific folder.  A rule that uses "from people" allows you to specify a list of specific email addresses rather than an entire domain.  The "from people" condition DOES NOT require you to have a contact entry for each person (address) in the list.
0
 

Author Comment

by:Rob Rudloff
ID: 40538797
OK,  I'll change the rule to "from people" and try again.
Thanks
0
 

Assisted Solution

by:Rob Rudloff
Rob Rudloff earned 0 total points
ID: 40544269
I did what you suggested, and fixed another problem (more on that later) and it seems to work.  
The other problem that was getting in my way was that I have several folders open in Outlook.  Plus (because of my setup for testing), I have a "photography" rule in two folders.  So, I was running the test, and it was adding the email address to the rule that I wasn't looking at.

A developer at my office suggested changing:
    Set olkCol = Session.DefaultStore.GetRules
to
    Set olkCol = Application.ActiveExplorer.CurrentFolder.Store.GetRules
and modified the script as follows.   He said he's not good with the Outlook object, so what do you think of the following code?
Thanks!

Sub AddToRule_Photography()
    Dim olkCol As Outlook.Rules
    Dim olkRul As Outlook.Rule
    Dim olkCnd As Outlook.ToOrFromRuleCondition
    Dim olkMsg As Outlook.MailItem
    
    Set olkCol = Application.ActiveExplorer.CurrentFolder.Store.GetRules
    
    For Each olkRul In olkCol
        If olkRul.Name = "Photography" Then
             For Each olkMsg In Application.ActiveExplorer.Selection
                If TypeName(olkRul) <> "Nothing" Then
                    Set olkCnd = olkRul.Conditions.From
                    olkCnd.Recipients.Add olkMsg.SenderEmailAddress
                    olkCnd.Recipients.ResolveAll
                    olkCol.Save True
                End If
            Next
            Exit For
        End If
        
    Next
                
    Set olkMsg = Nothing
    Set olkCnd = Nothing
    Set olkRul = Nothing

End Sub

Open in new window

0
 
LVL 76

Assisted Solution

by:David Lee
David Lee earned 2000 total points
ID: 40546631
I have a "photography" rule in two folders.

I'm not sure what you mean.  Folders don't have rules.  Only an Exchange message store (i.e. a mailbox on an Exchange server) has a rules collection.  Unless you have two different Exchange mailboxes defined in your profile, then you have a single message store which has one set of rules.  The code change proposed by the developer is okay if you have multiple Exchange message stores defined in your profile.  If you don't, then it's functionally equivalent to my original code with one difference.  If you select a message in a .pst file, then that change will give you an error because .pst files don't have rules collections.  The code I posted won't give the same error because it always gets the rules from the Exchange message store defined in your profile.
0
 

Author Closing Comment

by:Rob Rudloff
ID: 40555998
Now I understand the terminology -- Yes, I have multiple mailboxes:  2 on different Exchange servers and another that is POP.
Just for my education, I will put a rule in the POP account (.pst) and see it generate the error.

After showing this to the boss, he suggests adding a combo box (which means adding a form) that will show him the rules, and let him select to which rule it will add the "sender email address".  I will post my attempt at that code later, and post a link to it here, perhaps.

Thanks for your help!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article helps those who get the 0xc004d307 error when trying to rearm (reset the license) Office 2013 in a Virtual Desktop Infrastructure (VDI) and/or those trying to prep the master image for Microsoft Key Management (KMS) activation. (i.e.- C…
This article describes how to use a set of graphical playing cards to create a Draw Poker game in Excel or VB6.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
CodeTwo Sync for iCloud (http://www.codetwo.com/sync-for-icloud?sts=6554) automatically synchronizes your Outlook 2016, 2013, 2010 or 2007 folders with iCloud folders available via iCloud Control Panel. This lets you automatically sync them with…

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question