Checking for a Specific Message at a Set Interval


I put this post together for a Twitter user going by the name DerroldJess (DJ for short). DJ tweeted me asking if I could create a script that would check a mailbox every 15 minutes for a message with a specific subject, and display an alert if it did not find one. You can view the entire conversation here. The good news is that this is possible, although not from within Outlook. In order to make a check every 15 minutes, the solution needs a timer to trigger it. The only timer-like capability in Outlook is a reminder on a task or appointment, and for this that’s impractical. If the script only needed to run once a day, then I’d have gone that route and written this as an Outlook macro. Instead, I opted to write this using VBScript. VBScript runs outside of Outlook, so DJ can use Windows’ built-in task scheduler to run the task every 15 minutes.

The script itself is really very simple. It starts by creating an instance of Outlook, then searches the Inbox folder for messages with the subject DJ is looking for. If it doesn’t find any, then it displays a dialog-box alerting DJ to that fact. If instead it finds one or more of the messages, then it checks each one of them to see if it arrived within the last 15 minutes. If one of them is less than 15 minutes old, then the script falls through and does nothing. Otherwise, it displays a dialog-box alerting DJ to the fact that no message was received in the last 15 minutes.

As always, you should test the code thoroughly to make sure it does what you want and expect before putting it into production. While I tested the code before posting it, my environment may be different than yours and I may not have completely understood the goal.

Requirements.

This solution requires Outlook 2007 or later. The computer must be on and Windows running for the script to work.

Code and Instructions.

  1. Open Notepad.
  2. Copy the script and paste it into Notepad.
  3. Edit the code as desired. I included a comment line immediately before where you can make a change.
  4. Save the file with a .vbs extension. You can name it anything you want.
  5. Close Notepad.
  6. Create a task using Windows Task Scheduler. Set the task to run this script.
'Create some constants
'On the next line change the name of the script as desired
Const SCRIPT_NAME = "Check for Processor Report"
'On the next line edit the subject of the message the script is to look for
Const SUBJECT_TO_FIND = "59145822 ACE eSurvey_15minFeed_new - Processor Report"
'On the next line change the message the script displays if it does not find a report
Const DISPLAY_MSG = "I could not find a Processor Report message that arrived within the last 15 minutes."
Const olFolderInbox = 6

'Create some variables
Dim olkApp, olkSes, olkFld, olkCol, olkMsg, bolFound

'Connect to Outlook
Set olkApp = CreateObject("Outlook.Application")
Set olkSes = olkApp.GetNamespace("MAPI")
olkSes.Logon olkApp.DefaultProfileName

'Connect to the inbox and check for the subject messages
Set olkFld = olkSes.GetDefaultFolder(olFolderInbox)
Set olkCol = olkFld.Items.Restrict("[Subject]= '" & SUBJECT_TO_FIND & "'")
If olkCol.Count = 0 Then
    bolFound = False
Else
    For Each olkMsg In olkCol
        If DateDiff("n", olkMsg.ReceivedTime, Now) <= 15 Then
            bolFound = True
            Exit For
        End If
    Next
End If
If Not bolFound Then
    MsgBox DISPLAY_MSG, vbCritical + vbOKOnly, SCRIPT_NAME
End If
    
'Clean-up
olkSes.Logoff
Set olkMsg = Nothing
Set olkCol = Nothing
Set olkFld = Nothing
Set olkSes = Nothing
Set olkApp = Nothing
Advertisements

61 comments on “Checking for a Specific Message at a Set Interval

  1. Dave,

    This is Daniel again. i asked you to create the following script for me:

    '--&gt; Create some constants
        'On the next line change the name of the script as desired
        Const SCRIPT_NAME = "EMA Security Messages Sweep"
      
        'On the next line, change the name of the message store the search folder is in
        Const STORE_NAME = "NYSE Blue Environmental_2014"
      
        'On the next line, change the name of the search folder
        Const SEARCH_FOLDER = "Environmental Search Folder Sweep"
      
        'On the next line, change the number of minutes as desired
        Const ELAPSED_MINUTES = 15
      
        'On the next line, change the minimum number of messages required to trigger the alert email
        Const COUNT_THRESHOLD = 10
      
        Const olFolderInbox = 6
        Const olMailItem = 0
        Const olFormatPlain = 1
         
        Const ForReading = 1
        Const ForWriting = 2
        Const ForAppending = 8
         
        Const DEBUGGING = True
        
    '--&gt; Create some variables
        Dim olkApp, olkSes, olkSto, olkFld, olkMsg, intCnt, dicAdr, strAdr, intPtr, arrAdr, arrVal, strBuf, objFSO, objLog, strPth
        
    '--&gt; Initialize some variables
        If DEBUGGING Then
            On Error Resume Next
            Set objFSO = CreateObject("Scripting.FileSystemObject")
            strPth = Replace(WScript.ScriptFullName, ".vbs", ".log")
            Set objLog = objFSO.OpenTextFile(strPth, ForAppending, True)
            WriteLogEntry 1,"*** Begining Run"
        End If
        intCnt = 0
        strBuf = ""
        Set dicAdr = CreateObject("Scripting.Dictionary")
        dicAdr.Add "wregisadmin@wecc.biz", 0
        dicAdr.Add "jwebb@apx.com", 0
        dicAdr.Add "mrets@apx.com", 0
        dicAdr.Add "reserve@climateactionreserve.org", 0
        dicAdr.Add "gis@apx.com", 0
        dicAdr.Add "mirecs@apx.com", 0
        dicAdr.Add "acr@winrock.org", 0
        dicAdr.Add "vcs@apx.com", 0
        
    '--&gt; Connect to Outlook
        Set olkApp = CreateObject("Outlook.Application")
        Set olkSes = olkApp.GetNamespace("MAPI")
        olkSes.Logon olkApp.DefaultProfileName
        If DEBUGGING Then 
            WriteLogEntry 2, "Connect to Outlook"
            WriteLogEntry 3, "olkApp = " &amp; TypeName(olkApp)
            WriteLogEntry 3, "olkSes = " &amp; TypeName(olkSes)
        End If
        
    '--&gt; Connect to the search folder and count the number of items received in the last ELAPSED_MINUTES minutes
        If DEBUGGING Then WriteLogEntry 2, "Processing search folder"
        Set olkSto = olkSes.Stores.Item(STORE_NAME)
        If DEBUGGING Then WriteLogEntry 3, "olkSto = " &amp; TypeName(olkSto)
        Set olkFld = olkSto.GetSearchFolders.Item(SEARCH_FOLDER)
        If DEBUGGING Then WriteLogEntry 3, "olkFld = " &amp; TypeName(olkFld)
        If olkFld.Items.Count &gt; 0 Then
            If DEBUGGING Then WriteLogEntry 3, "There are items to process"
            For Each olkMsg In olkFld.Items
                If DateDiff("n", olkMsg.ReceivedTime, Now)  If there were COUNT_THRESHOLD or more items, then send an email
        If DEBUGGING Then WriteLogEntry 2, "Checking Counts"
        If intCnt &gt;= COUNT_THRESHOLD Then
            If DEBUGGING Then WriteLogEntry 3, "Count exceeds threshold"
            arrAdr = dicAdr.Keys
            arrVal = dicAdr.Items
            For intPtr = LBound(arrAdr) To UBound(arrAdr)
                strBuf = strBuf &amp; PadRight(arrAdr(intPtr), 35) &amp; vbTab &amp; arrVal(intPtr) &amp; vbCrLf
            Next
            If DEBUGGING Then WriteLogEntry 3, "Creating notification email"
            Set olkMsg = olkApp.CreateItem(olMailItem)
            With olkMsg
                'On the next two lines, edit the message subject and who it will be sent to
                .Subject = "Alert - More than " &amp; COUNT_THRESHOLD &amp; " items received in the last " &amp; ELAPSED_MINUTES &amp; " minutes"
                .To = "helpdesk@apx.com"
                .BodyFormat = olFormatPlain
                .Body = "I found " &amp; intCnt &amp; " item(s) received within the last " &amp; ELAPSED_MINUTES &amp; " minutes." &amp; vbCrLf &amp; vbCrLf &amp; _
                        "Here are the counts for the specific addresses you asked me to watch for " &amp; vbCrLf &amp; vbCrLf &amp; strBuf
                .Send
            End With
        End If
        
    '--&gt; Disconnect from Outlook
        If DEBUGGING Then WriteLogEntry 2, "Disconnecting from Outlook"
        olkSes.Logoff
        Set olkMsg = Nothing
        Set olkFld = Nothing
        Set olkSto = Nothing
        Set olkSes = Nothing
        Set olkApp = Nothing
      
    '--&gt; Cleanup other objects
        If DEBUGGING Then WriteLogEntry 2, "Cleaning up objects"
        Set dicAdr = Nothing
      
    '--&gt; Terminate the script
        If DEBUGGING Then 
            WriteLogEntry 1, "*** Ending Run"
            objLog.Close
            Set objLog = Nothing
            Set objFSO = Nothing
        End If
        WScript.Quit
      
    Function PadRight(strVal, intLen)
        Dim intTmp
        intTmp = Len(strVal)
        If intTmp &lt; intLen Then
            PadRight = strVal &amp; String(intLen - intTmp, &quot; &quot;)
        Else
            PadRight = strVal
        End If
    End Function
     
    Sub WriteLogEntry(intLevel, strMsg)
        objLog.Writeline &quot;[&quot; &amp; Now &amp; &quot;]&quot; &amp; Space(intLevel * 4) &amp; Replace(strMsg,vbCrLf,&quot;&quot;)
    End Sub
    

    Looks like I am having some issues again. Recently, we recieved a new Lenovo PC at work and I tried adding the following script to the task scheduler. Based on the history of the task scheduler, the script is running. However, there is no log entry text file that appears so I am unable to confirm if the script is actually working correctly. Any chance, you could give me a hand with this?

    Thanks!

    DJ

  2. Dave,

    I tested the script and it works like a charm! Thank you so much for all the help! I truly appreciate you sticking with me throughout this process. Take care!

    Best Regards,

    Daniel

    • Dave,

      Good afternoon Dave, it is Daniel again. So far the VBScript has been working fantastically! I know the code provides the total amount of e-mails that are gathered by the search folder during a 15 minute interval. However, is there a way that the code could count the number of messages received from a certain e-mail address (Please see below for the addresses) and present that data in the e-mail alert? Thank you very much for the help!

      Here are some e-mail addresses that the code could track:
      wregisadmin@wecc.biz
      jwebb@apx.com
      mrets@apx.com
      Reserve@climateactionreserve.org
      gis@apx.com
      mirecs@apx.com
      acr@winrock.org
      vcs@apx.com

      Best Regards,

      Daniel

    • Daniel,

      Sure, that’s possible. Do you want the alert to show the stats for all of these addresses each time or only show the counts for those addresses where the count is greater than zero?

    • Dave,

      Sorry for the late response! I prefer showing the counts for the addresses that have a count greater than zero please. Thanks you so much!

      Best Regards,

      Daniel

    • Daniel,

      No worries.

      I thought I had a copy of the code you’re using, but I don’t. If you’ll post/send me a copy, then I’ll make these changes.

    • Dave,

      Here is a copy of the current code. Thank you!

      'Create some constants
      'On the next line change the name of the script as desired
      Const SCRIPT_NAME = "EMA Security Messages Sweep"
      'On the next line, change the name of the message store the search folder is in
      Const STORE_NAME = "NYSE Blue Environmental_2014"
      'On the next line, change the name of the search folder
      Const SEARCH_FOLDER = "Environmental Search Folder Sweep"
      Const olFolderInbox = 6
      Const olMailItem = 0
      Const olFormatPlain = 1
       
      'Create some variables
      Dim olkApp, olkSes, olkSto, olkFld, olkMsg, intCnt
       
      'Initialize some variables
      intCnt = 0
       
      'Connect to Outlook
      Set olkApp = CreateObject("Outlook.Application")
      Set olkSes = olkApp.GetNamespace("MAPI")
      olkSes.Logon olkApp.DefaultProfileName
       
      'Connect to the search folder and count the number of items received in the last 15 minutes
      Set olkSto = olkSes.Stores.Item(STORE_NAME)
      Set olkFld = olkSto.GetSearchFolders.Item(SEARCH_FOLDER)
      If olkFld.Items.Count &gt; 0 Then
          For Each olkMsg In olkFld.Items
              If DateDiff("n", olkMsg.ReceivedTime, Now) = 10 Then
          Set olkMsg = olkApp.CreateItem(olMailItem)
          With olkMsg
              'On the next two lines, edit the message subject and who it will be sent to
              .Subject = "Alert - More than 10 items received in the last 15 minutes"
              .To = "helpdesk@apx.com"
              .BodyFormat = olFormatPlain
              .Body = "I found " &amp; intCnt &amp; " item(s) received within the last 15 minutes."
              .Send
          End With
      End If
       
      'Clean-up
      olkSes.Logoff
      Set olkMsg = Nothing
      Set olkFld = Nothing
      Set olkSto = Nothing
      Set olkSes = Nothing
      Set olkApp = Nothing
      

      Best Regards,

      Daniel

    • Daniel,

      I think this should do it. I’ve not tested this so there may be errors.

      '--> Create some constants
          'On the next line change the name of the script as desired
          Const SCRIPT_NAME = "EMA Security Messages Sweep"
      
          'On the next line, change the name of the message store the search folder is in
          Const STORE_NAME = "NYSE Blue Environmental_2014"
      
          'On the next line, change the name of the search folder
          Const SEARCH_FOLDER = "Environmental Search Folder Sweep"
      
          'On the next line, change the number of minutes as desired
          Const ELAPSED_MINUTES = 15
      
          'On the next line, change the minimum number of messages required to trigger the alert email
          Const COUNT_THRESHOLD = 10
      
          Const olFolderInbox = 6
          Const olMailItem = 0
          Const olFormatPlain = 1
        
      '--> Create some variables
          Dim olkApp, olkSes, olkSto, olkFld, olkMsg, intCnt, dicAdr, strAdr, intPtr, arrAdr, arrVal, strBuf
        
      '--> Initialize some variables
          intCnt = 0
          strBuf = ""
          Set dicAdr = CreateObject("Scripting.Dictionary")
          dicAdr.Add "wregisadmin@wecc.biz", 0
          dicAdr.Add "jwebb@apx.com", 0
          dicAdr.Add "mrets@apx.com", 0
          dicAdr.Add "reserve@climateactionreserve.org", 0
          dicAdr.Add "gis@apx.com", 0
          dicAdr.Add "mirecs@apx.com", 0
          dicAdr.Add "acr@winrock.org", 0
          dicAdr.Add "vcs@apx.com", 0
        
      '--> Connect to Outlook
          Set olkApp = CreateObject("Outlook.Application")
          Set olkSes = olkApp.GetNamespace("MAPI")
          olkSes.Logon olkApp.DefaultProfileName
        
      '--> Connect to the search folder and count the number of items received in the last ELAPSED_MINUTES minutes
          Set olkSto = olkSes.Stores.Item(STORE_NAME)
          Set olkFld = olkSto.GetSearchFolders.Item(SEARCH_FOLDER)
          If olkFld.Items.Count > 0 Then
              For Each olkMsg In olkFld.Items
                  If DateDiff("n", olkMsg.ReceivedTime, Now) <= ELAPSED_MINUTES Then
                      intCnt = intCnt + 1
                      strAdr = LCase(olkMsg.SenderEmailAddress)
                      If dicAdr.Exists(strAdr) Then
                          dicAdr(strAdr) = dicAdr(strAdr) + 1
                      End If
                  End If
              Next
          End If
      
      '--> If there were COUNT_THRESHOLD or more items, then send an email
          If intCnt >= COUNT_THRESHOLD Then
              arrAdr = dicAdr.Keys
              arrVal = dicAdr.Items
              For intPtr = LBound(arrAdr) To UBound(arrAdr)
                  strBuf = strBuf & PadRight(arrAdr(intPtr), 35) & vbTab & arrVal(intPtr) & vbCrLf
              Next
              Set olkMsg = olkApp.CreateItem(olMailItem)
              With olkMsg
                  'On the next two lines, edit the message subject and who it will be sent to
                  .Subject = "Alert - More than " & COUNT_THRESHOLD & " items received in the last " & ELAPSED_MINUTES & " minutes"
                  .To = "helpdesk@apx.com"
                  .BodyFormat = olFormatPlain
                  .Body = "I found " & intCnt & " item(s) received within the last " & ELAPSED_MINUTES & " minutes." & vbCrLf & vbCrLf & _
                          "Here are the counts for the specific addresses you asked me to watch for " & vbCrLf & vbCrLf & strBuf
                  .Send
              End With
          End If
        
      '--> Disconnect from Outlook
          olkSes.Logoff
          Set olkMsg = Nothing
          Set olkFld = Nothing
          Set olkSto = Nothing
          Set olkSes = Nothing
          Set olkApp = Nothing
      
      '--> Cleanup other objects
          Set dicAdr = Nothing
      
      '--> Terminate the script
          WScript.Quit
      
      Function PadRight(strVal, intLen)
          Dim intTmp 
          intTmp = Len(strVal)
          If intTmp < intLen Then
              PadRight = strVal & String(intLen - intTmp, " ")
          Else
              PadRight = strVal
          End If
      End Function
      
    • Dave,

      I have placed the script in the task manager without any errors windows popping up. However, when I flooded the inbox with targeted e-mails nothing happened. The e-mail message alerting me of the 10 messages with 15 minutes was not even sent. Do the e-mails have to be from the e-mail addresses I sent you in order for the alert to pop up? Maybe having the script showing the stats for all the e-mail addresses each time a better option?

      Thanks,

      Daniel

    • Dave,

      Disregard my last response. I tested the code out and it works perfectly! Just forgot to save the notepad file as a vbs. Thank you again for the help Dave! You are the best!

      Best Regards,

      Daniel

    • Dave,

      Real quick question. Is the script designed to send an alert e-mail out only when more than zero messages are received for a specified e-mail address (i.e., mrets@apx.com) ? Because I forwarded fake security messages from my personnel e-mail (djuarez@apx.com) to test out the script today, but no alert e-mails are sent to the help desk inbox. Yesterday the script worked when I forwarded test messages from my personnel e-mail to the help desk inbox. However, the script seemed to work because there was a real security message that was received in the inbox while I was forwarding test e-mails.

      Thanks,

      Daniel

    • Daniel,

      Is the script designed to send an alert e-mail out only when more than zero messages are received for a specified e-mail address?
      No. The script is designed to send the alert e-mail if the total message count received in the last interval specified by ELAPSED_MINUTES is greater than or equal to the value specified by COUNT_THRESHOLD. If you didn’t change those values, then that would be 10 messages within the last 15 minutes. If there were fewer than than COUNT_THRESHOLD messages received in the last ELAPSED_MINUTES, then the script does not send an alert e-mail.

    • Dave,

      Got it, thank you for the clarification! Couple more question. I noticed that two e-mail alert notifications are sent simultaneously when the threshold is met. Is there any way to troubleshoot that? Lastly, is there any “Triggers” that you suggest in the Task Scheduler to have the script constantly running 24/7? Right now my trigger for the task is “task creation or modified”. I previously had the trigger as “At startup,” but it did not seem to run unless the computers were rebooted.

    • Daniel,

      I don’t see how the script could send two e-mail alerts. The code starts by counting the number of items received in the last X minutes. It then checks to see if that count is greater than or equal to the threshold. If it is, then it sends a message. Unless the script is running twice, back to back, then I don’t see how it could send two messages.

      The only trigger you need is On a schedule. Create a task. Click the Begin the task pulldown and select On a schedule. Set the task to run Daily and to Recur every 1 days. Under Advanced settings check the Repeat task every box and select 15 minutes from the pulldown. Click the for a duration of pulldown and select Indefinitely. That should do it.

    • Dave,

      Okay, I understand. I will keep my eye on it in the future to see what happens, but right now the script is doing what it is designed to do. Thanks for the advice, Dave!

      Best Regards,

      Daniel

    • Dave,

      Recently, the script stopped working and I thought it might have been due to new folders being made for 2015. I updated the vbscript to accommodate for the new 2015 folders created in outlook, but when I run the task in the scheduler nothing happens. The task has the status of “Running.” However, the history shows “Task Completed” after starting it but the task does not seem to run every 15 minutes as scheduled. Any insight on how to get the task to run again as scheduled?

      Thanks!

      Daniel

    • Daniel,

      What happens if you run the script manually instead of having the scheduler run it? Does it work properly then?

  3. Dave,

    I attempted to test out the vbs coding you provided me and I am getting an error when I try to run the script in the task manager. I am getting an “Unterminated string constant error”/Code:800A0409/Line:5/Char:37. Here is the code I have so far (sorry! I do not know how to present the code in a separate window!). For the constants (i.e, the store name and search folder), do I need the full file paths?

    ‘Create some constants
    ‘On the next line change the name of the script as desired
    Const SCRIPT_NAME = “EMA Sweep in Last 15 Minutes”
    ‘On the next line, change the name of the message store the search folder is in
    Const STORE_NAME = “helpdesk@apx.com
    ‘On the next line, change the name of the search folder
    Const SEARCH_FOLDER = “Environmental Search Folder Sweep”
    Const olFolderInbox = 6
    Const olMailItem = 0
    Const olFormatPlain = 1

    ‘Create some variables
    Dim olkApp, olkSes, olkSto, olkFld, olkMsg, intCnt

    ‘Initialize some variables
    intCnt = 0

    ‘Connect to Outlook
    Set olkApp = CreateObject(“Outlook.Application”)
    Set olkSes = olkApp.GetNamespace(“MAPI”)
    olkSes.Logon olkApp.DefaultProfileName

    ‘Connect to the search folder and count the number of items received in the last 15 minutes
    Set olkSto = olkSes.Stores.Item(STORE_NAME)
    Set olkFld = olkSto.GetSearchFolders.Item(SEARCH_FOLDER)
    If olkFld.Items.Count > 0 Then
    For Each olkMsg In olkFld.Items
    If DateDiff(“n”, olkMsg.ReceivedTime, Now) = 10 Then
    Set olkMsg = olkApp.Create Item(olMailItem)
    With olkMsg
    ‘On the next two lines, edit the message subject and who it will be sent to
    .Subject = “Alert – More than 10 items received in the last 15 minutes”
    .To = “helpdesk@apx.com”
    .BodyFormat = olFormatPlain
    .Body = “I found ” & intCnt & ” item(s) received within the last 15 minutes.”
    .Send
    End With
    End If

    ‘Clean-up
    olkSes.Logoff
    Set olkMsg = Nothing
    Set olkFld = Nothing
    Set olkSto = Nothing
    Set olkSes = Nothing
    Set olkApp = Nothing

    Thanks,

    DJ

    • DJ,

      You need to terminate line 5 with a double-quote. In other words, change

      Const STORE_NAME = “helpdesk@apx.com
      

      to

      Const STORE_NAME = “helpdesk@apx.com"
      
    • Dave,

      I just tested the script again with the changes you suggested. I am now having a “Invalid Character Error/Character 21/Line 3/ code 800A0408.” I did some searching around the internet regarding this error and one troubleshooting tip was ensuring that ANSI was the coding being used when saving the notepad file. I saved the file a again and ensured that ANSI was the coding, but the error still remains.

      Regards,

      Daniel

    • Dave,

      I tried this: “Const SCRIPT_NAME = EMA Sweep in the Last 15 minutes” in line 3. I received the same error for line 3/character 1. I tried Const SCRIPT_NAME = “EMA Sweep in the Last 15 minutes” in line 3 and I received the same error but for line 5/character 20.

    • Daniel,

      No, the quotes need to be at the beginning of the value of the constant, not before the constant declaration. In other words

      Const SCRIPT_NAME = "EMA Sweep in the Last 15 minutes"
      

      But I want you to type the quotes in rather than cutting and pasting them from here.

    • Dave,

      I was able to delete the quotation marks and type them in manually around “EMA Sweep in Last 15 Minutes.” However, when I tried testing the vbs in the windows task manager, a new error came up concerning line 36/character 32/expected end of statement error/code 800A0401 : Set olkMsg = olkApp.Create Item(olMailItem).

      Thanks,

      DJ

    • Dave,

      There is no period at the end of that command. This is how it looks in the code.

      Set olkMsg = olkApp.Create Item(olMailItem)

    • Daniel,

      Is there a space between Create and Item as there is in your example? If there is, then please remove the space.

    • Dave,

      For line 24 and 25 :
      24 – Set olkSto = olkSes.Stores.Item(STORE_NAME)
      25 – Set olkFld = olkSto.GetSearchFolders.Item(SEARCH_FOLDER)

      When I enter the store_name and search_folder, am I using quotation marks? i.e., Set olkSto = olkSes.Stores.Item(“helpdesk@apx.com”)?

      Thanks,

      Daniel

    • Daniel,

      You shouldn’t edit either of those lines. You need to edit the constants at the top of the script per my comments in the script. Edit these lines

      'On the next line, change the name of the message store the search folder is in
      Const STORE_NAME = "Mailbox - Doe, John"
      'On the next line, change the name of the search folder
      Const SEARCH_FOLDER = "My Search"
      

      Yes, you’ll enclose the values in quotes. For example, if “helpdesk@apx.com” is the name of the store, then you’ll change this line

      Const STORE_NAME = "Mailbox - Doe, John"
      

      to

      Const STORE_NAME = "helpdesk@apx.com"
      
    • Dave,

      I am not sure if you got my last reply. I was wondering if the error was due to not including a complete search folder path on line #7? Please respond when you can.

      Thanks,

      Daniel (DJ)

    • Hi, Daniel.

      I’m not sure if I did or not. Did you send your reply by email or did you post it here?

      That aside, no the folder name on line 7 is just the name of the search folder. There is no path.

    • Dave,

      I believe I posted another error I encountered on this website. I will send you the details of the error later.

      Thanks,

      Daniel

    • Dave,

      Sorry for the late response. I have tried running the script again will all the suggested fixes and I received this error. Error: “The attempted operation failed. And object could not be found”/Line 26/Char. 1/Code:8004010F/Source: Microsoft Outlook. I will continue to research this error to see if I can trouble shoot on my end.

      Thanks,

      DJ

    • Daniel,

      Based on the error message I have to assume that olkFld does not point to a folder as it should. The only reason for that would be that either the store name or search folder name given is invalid.

    • Dave,

      I have changed the store name and no errors have come up yet when running the script. Quick question, can Outlook be open in the background while this script runs? Also, does this script store messages or data on your computer when it runs? Basically, I want to know if this script is “taxing” on the computer’s memory, etc.

      Best Regards,

      Daniel

    • Daniel,

      Yes, Outlook can be open while the script runs. No, the script doesn’t store anything and should not tax the computer. It might slow Outlook down for a few seconds while it counts the messages, but that should be the extent of the impact.

    • Good Morning Dave,

      Yes, I have been manually running the script the whole time. It does show the status as “Running” but the history shows that the task only ran once when I initially started the task. It is not running every 15 minutes as commanded. I did make some changes to the search folder name in the script but that is about it. The script looks fine from my end.

    • Hey, Daniel.

      When I said “manually” I didn’t mean running the scheduled task manually. I mean run the script manually, as in you double-click the script. I’m trying to determine if the script is screwing up somehow or if it’s task scheduler that’s the problem.

  4. Hello Dave,

    To be more specific, these are the words that I would be searching for in the subject : Security|SQL|Unsafe|Error|Unauthorized. I believe that a search folder might be necessary with these words. Do you mind informing me how to make a search folder? Or I could possibly Google it.

    As for the 15 minute interval, I just need the code to check the current 15 minute interval (as you pointed out) for messages that contain the keywords in the subject. If there are 10 or more messages with keywords in the subject received within the current 15 minute interval, then an e-mail will be sent to notify that the threshold is exceeded. That’s it. Hopefully we are on the same page. Thank you Dave for the response and I look forward to testing this out!

    Regards,

    DJ

    • Daniel,

      To create an Outlook search folder, right-click on a Search Folders folder in the navigation pane (the pane on the far left) and select “New Search Folder”. When the “New Search Folder” dialog-box appears, scroll to the bottom and select “Create a custom Search Folder”. Now, click the “Choose” button to set the search folder name and to set the criteria. You can create a single search that will find any message with one of those keywords in its subject.

      Once you have the search folder set up, you can use the script below to check it for items received within the last 15 minutes. If there are ten or more, then the script sends a message to the address specified.

      'Create some constants
      'On the next line change the name of the script as desired 
      Const SCRIPT_NAME = "Check for Items Received in Last 15 Minutes"
      'On the next line, change the name of the message store the search folder is in
      Const STORE_NAME = "Mailbox - Doe, John
      'On the next line, change the name of the search folder
      Const SEARCH_FOLDER = "My Search"
      Const olFolderInbox = 6
      Const olMailItem = 0
      Const olFormatPlain = 1
      
      'Create some variables
      Dim olkApp, olkSes, olkSto, olkFld, olkMsg, intCnt
      
      'Initialize some variables
      intCnt = 0
      
      'Connect to Outlook
      Set olkApp = CreateObject("Outlook.Application")
      Set olkSes = olkApp.GetNamespace("MAPI") 
      olkSes.Logon olkApp.DefaultProfileName
      
      'Connect to the search folder and count the number of items received in the last 15 minutes
      Set olkSto = olkSes.Stores.Item(STORE_NAME) 
      Set olkFld = olkSto.GetSearchFolders.Item(SEARCH_FOLDER)
      If olkFld.Items.Count > 0 Then
          For Each olkMsg In olkFld.Items
              If DateDiff("n", olkMsg.ReceivedTime, Now) <= 15 Then
                  intCnt = intCnt + 1
              End If
          Next
      End If
      
      'If there are ten or more items received in the last 15 minutes, then send an email
      If intCnt >= 10 Then
          Set olkMsg = olkApp.Create Item(olMailItem)
          With olkMsg
              'On the next two lines, edit the message subject and who it will be sent to
              .Subject = "Alert - More than 10 items received in the last 15 minutes"
              .To = "someoen@company.com"
              .BodyFormat = olFormatPlain
              .Body = "I found " & intCnt & " item(s) received within the last 15 minutes."
              .Send
          End With
      End If
      
      'Clean-up
      olkSes.Logoff
      Set olkMsg = Nothing
      Set olkFld = Nothing
      Set olkSto = Nothing
      Set olkSes = Nothing
      Set olkApp = Nothing
      
    • Dave,

      Just manually started the script i received the following error in the window:

      Line: 43
      Char: 5
      Error: The attempted operation failed. An object could not be found.
      Code:8004010F
      Source: Microsoft Outlook

    • Dave,

      Scratch that previous comment Dave with the error. I have double clicked on the vbscript on another machine, but I am not certain if it is working or not. Is there a way to determine that? Do I have to test it by flooding my e-mail box with messages?

      Thanks!

      Daniel

    • Daniel,

      I wanted to see if the script was throwing any errors. You shouldn’t need to flood your mailbox with messages, but your there should be a couple of messages there for it to process. If you still can’t determine if the script is working properly, then I can add some code to write an event log we can use to determine what’s happening.

  5. Good morning Dave,

    I am just following up to confirm that you received my question about vbs scripting/Revision 33.

    Thank you,

    Daniel (DJ)

    • Hi, Daniel.

      Yes, I received your question. I’ve been off-line since the 18th and am just now getting back to answering comments. It may be a few days before I get to your question, but I will respond.

    • Dave,

      I did run the script manually yesterday and found that it did work when I flooded messages into the inbox. As for any errors popping up when running it, I did not see any. You think the event log should still be made based on that information?

      Thanks!

      Daniel

    • Daniel,

      Please try this version. It will create a log file in the folder the script is in. The log file will have the same name as the script with an extension of .log. It will be a plain text file. After the scheduled task has had a chance to run a couple of times, please check the log file to see if it has anything in it. If it doesn’t, then the Windows isn’t running the scheduled task. If the log file does have output, but the script doesn’t appear to have done what it is supposed to do, then send me the log file and I’ll see if I can figure out what’s happening.

      '--> Create some constants
          'On the next line change the name of the script as desired
          Const SCRIPT_NAME = "EMA Security Messages Sweep"
       
          'On the next line, change the name of the message store the search folder is in
          Const STORE_NAME = "NYSE Blue Environmental_2014"
       
          'On the next line, change the name of the search folder
          Const SEARCH_FOLDER = "Environmental Search Folder Sweep"
       
          'On the next line, change the number of minutes as desired
          Const ELAPSED_MINUTES = 15
       
          'On the next line, change the minimum number of messages required to trigger the alert email
          Const COUNT_THRESHOLD = 10
       
          Const olFolderInbox = 6
          Const olMailItem = 0
          Const olFormatPlain = 1
          
          Const ForReading = 1
          Const ForWriting = 2
          Const ForAppending = 8
          
          Const DEBUGGING = True
         
      '--> Create some variables
          Dim olkApp, olkSes, olkSto, olkFld, olkMsg, intCnt, dicAdr, strAdr, intPtr, arrAdr, arrVal, strBuf, objFSO, objLog, strPth
         
      '--> Initialize some variables
      	If DEBUGGING Then
      		On Error Resume Next
      		Set objFSO = CreateObject("Scripting.FileSystemObject")
      		strPth = Replace(WScript.ScriptFullName, ".vbs", ".log")
      		Set objLog = objFSO.OpenTextFile(strPth, ForAppending, True)
      		WriteLogEntry 1,"*** Begining Run"
      	End If
          intCnt = 0
          strBuf = ""
          Set dicAdr = CreateObject("Scripting.Dictionary")
          dicAdr.Add "wregisadmin@wecc.biz", 0
          dicAdr.Add "jwebb@apx.com", 0
          dicAdr.Add "mrets@apx.com", 0
          dicAdr.Add "reserve@climateactionreserve.org", 0
          dicAdr.Add "gis@apx.com", 0
          dicAdr.Add "mirecs@apx.com", 0
          dicAdr.Add "acr@winrock.org", 0
          dicAdr.Add "vcs@apx.com", 0
         
      '--> Connect to Outlook
          Set olkApp = CreateObject("Outlook.Application")
          Set olkSes = olkApp.GetNamespace("MAPI")
          olkSes.Logon olkApp.DefaultProfileName
          If DEBUGGING Then 
          	WriteLogEntry 2, "Connect to Outlook"
          	WriteLogEntry 3, "olkApp = " & TypeName(olkApp)
          	WriteLogEntry 3, "olkSes = " & TypeName(olkSes)
          End If
         
      '--> Connect to the search folder and count the number of items received in the last ELAPSED_MINUTES minutes
      	If DEBUGGING Then WriteLogEntry 2, "Processing search folder"
          Set olkSto = olkSes.Stores.Item(STORE_NAME)
          If DEBUGGING Then WriteLogEntry 3, "olkSto = " & TypeName(olkSto)
          Set olkFld = olkSto.GetSearchFolders.Item(SEARCH_FOLDER)
          If DEBUGGING Then WriteLogEntry 3, "olkFld = " & TypeName(olkFld)
          If olkFld.Items.Count > 0 Then
          	If DEBUGGING Then WriteLogEntry 3, "There are items to process"
              For Each olkMsg In olkFld.Items
                  If DateDiff("n", olkMsg.ReceivedTime, Now) <= ELAPSED_MINUTES Then
                  	If DEBUGGING Then WriteLogEntry 4, "Hit: " & olkMsg.subject
                      intCnt = intCnt + 1
                      strAdr = LCase(olkMsg.SenderEmailAddress)
                      If dicAdr.Exists(strAdr) Then
                          dicAdr(strAdr) = dicAdr(strAdr) + 1
                      End If
                  End If
              Next
          End If
       
      '--> If there were COUNT_THRESHOLD or more items, then send an email
      	If DEBUGGING Then WriteLogEntry 2, "Checking Counts"
          If intCnt >= COUNT_THRESHOLD Then
          	If DEBUGGING Then WriteLogEntry 3, "Count exceeds threshold"
              arrAdr = dicAdr.Keys
              arrVal = dicAdr.Items
              For intPtr = LBound(arrAdr) To UBound(arrAdr)
                  strBuf = strBuf & PadRight(arrAdr(intPtr), 35) & vbTab & arrVal(intPtr) & vbCrLf
              Next
              If DEBUGGING Then WriteLogEntry 3, "Creating notification email"
              Set olkMsg = olkApp.CreateItem(olMailItem)
              With olkMsg
                  'On the next two lines, edit the message subject and who it will be sent to
                  .Subject = "Alert - More than " & COUNT_THRESHOLD & " items received in the last " & ELAPSED_MINUTES & " minutes"
                  .To = "helpdesk@apx.com"
                  .BodyFormat = olFormatPlain
                  .Body = "I found " & intCnt & " item(s) received within the last " & ELAPSED_MINUTES & " minutes." & vbCrLf & vbCrLf & _
                          "Here are the counts for the specific addresses you asked me to watch for " & vbCrLf & vbCrLf & strBuf
                  .Send
              End With
          End If
         
      '--> Disconnect from Outlook
      	If DEBUGGING Then WriteLogEntry 2, "Disconnecting from Outlook"
          olkSes.Logoff
          Set olkMsg = Nothing
          Set olkFld = Nothing
          Set olkSto = Nothing
          Set olkSes = Nothing
          Set olkApp = Nothing
       
      '--> Cleanup other objects
      	If DEBUGGING Then WriteLogEntry 2, "Cleaning up objects"
          Set dicAdr = Nothing
       
      '--> Terminate the script
      	If DEBUGGING Then 
      		WriteLogEntry 1, "*** Ending Run"
      		objLog.Close
      		Set objLog = Nothing
      		Set objFSO = Nothing
      	End If
          WScript.Quit
       
      Function PadRight(strVal, intLen)
          Dim intTmp
          intTmp = Len(strVal)
          If intTmp < intLen Then
              PadRight = strVal & String(intLen - intTmp, " ")
          Else
              PadRight = strVal
          End If
      End Function
      
      Sub WriteLogEntry(intLevel, strMsg)
      	objLog.Writeline "[" & Now & "]" & Space(intLevel * 4) & Replace(strMsg,vbCrLf,"")
      End Sub
      
  6. Dave,

    While looking through your webpage, I discovered the solution you gave to DerroldJess under the topic, “Checking for a Specific Message at a Set Interval.” I know that we have been working with Revision 33 posted in the “Exporting Outlook Messages to Excel,” but I am curious to test out DerroldJess’s solution. I was wondering if some modifications could be made to this code to meet my needs (please see below):

    1) Is it possible change the line: Const SUBJECT_TO_FIND = “59145822 ACE eSurvey_15minFeed_new – Processor Report” to search for certain words in the inbox? (similar to revision 33 – look for specific words in the subject line rather than a specific subject). If not, can more subjects be added for the code to search for.

    2) If messages with certain subjects are received, is there a way for the code to count the number of messages recieved within the 15minutes intervals and send an e-mail notification ? For example, if 10 messages with a specific subject are detected within 15 minutes an e-mail notification will be received.

    3) If this cannot be accomplished or just complicates things, then I am okay with a message box telling me that no messages were received in the 15 minute span. E-mail notifications when no messages are received would be a nice addition as well.

    Again, sorry for shifting gears and having you start all over again. I really appreciate the time and effort you put in to help. I can’t thank you enough!

    Regards,

    Daniel (DJ)

    • Daniel,

      1. Yes, I can modify the code to search for certain keywords in the subject line. The words must be unique (i.e. not part of some other word) for this to work. For example, if one of the keywords was “press”, then the code would get hits on words containing “press” such as “impress”, “depress”, “wordpress”, etc. Depending on the number of messages and keywords the code has to search, it might be better to create a search folder in Outlook that does the searching and have the code read the search folder rather than building the search into the code.

      2. Yes, I can modify the code to count the number of messages that have one or more of the keywords in the subject line and have it send a message if the count exceeds some threshold. I’m not sure what you mean when you say “within the 15 minute intervals”. It’s the plural “intervals” that’s tripping me up. The code will perform the check on the current 15 minute interval (singular) not the current 15 minute interval and some set number of past 15 minute intervals (plural).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s