Link to home
Start Free TrialLog in
Avatar of Jose Rivera-Hernandez
Jose Rivera-HernandezFlag for United States of America

asked on

MS Outlook search for attachments with certain subjects

I have an secondary account in which I monitor our company's email, the problem is that the emails get forwarded as an Attachment from the encryption system we have.

So I have to open each email which has the same subject and same body content, and then I open the attachment which is the actual email forwarded.

I would like to know if there is script, macro, or solution that would scan the Exchange account and filter out those emails that have a subject of "Out of Office Reply" "Read:...." or any other particular keywords.

Thank you,

J
Avatar of Kash
Kash
Flag of United Kingdom of Great Britain and Northern Ireland image

i am not sure what you are asking can be done. you have t loosen up security a bit so that emails get delivered in a normal fasion then you could search for them. Others may add with a better solution
Hi, hernandez5999.

Yes, that's possible.  What do you want to do with the messages that match those search terms?
Avatar of Jose Rivera-Hernandez

ASKER

Well I want to move them over to a separate folder if that can't be done then delete them which is what I would do eventually.

I only want to keep the emails that need to be reviewed, all those with "Auto Reply" or with particular key words are just wasting my time.

Thanks and let me know how is that possible.

J
Do the message attachments have a file name that matches the subject line of the message?  If not, what are the file names like?
Ok here is how it is:

I get hundreds of emails into this Outlook account. Each email has the same subject and includes an email attached.

The email attached is what I want to filter.

example:

Email 1:  Subject: Email Forwarded see attachment
               Email attached:  Subject: Auto Reply xxxxx

Email 2:  Subject: Email Forwarded see attachment
               Email attached:  Subject: Hi how are you!

Email 3:  Subject: Email Forwarded see attachment
               Email attached:  Subject: Here is my SSN card

Email 4:  Subject: Email Forwarded see attachment
               Email attached:  Subject: Out of Office xxxx

Email 1:  Subject: Email Forwarded see attachment
               Email attached:  Subject: Your credit card statement

So as you can see there are 5 emails with the same subject, but each has a different email attached. I want to sort or filter by the subject of THOSE emails, so I can filter the "Out of Office", "Auto Reply", etc... emails and only be left with those that are important to read.

How can this be accomplished?

J
I understand, but that's not what I was asking about.  The original emails show up as attachments.  Attachments have file names.  My question is, does the file name of the attachment match the subject of the original message?  Here's why I'm asking.  If the file name of the attachment matches the subject, then the process is much simpler.  Scan through the list of attachment file names checking each to see if it matches one of the patterns you want to filter out.  The code for that is very simple.  If, however, the file name does not match the subject, then the code will need to save each attachment to disk, open the item, and check the subject.  Compared to the code required for matching file names, this code is more complex.  Not exceedingly so, but it is more complicated.  I don't want to write an unnecessarily complex solution if I can take the simpler route of matching against the attachment's file name.  Does that make sense?
Yes the attachment name matches the Subject of the email.
This should do what you want.  This solution will only work in Outlook 2007 and later.

To add the code to Outlook 2007

1.  Start Outlook
2.  Press ALT+F11 to open the Visual Basic Editor
3.  If not already expanded, expand Microsoft Office Outlook Objects and click on ThisOutlookSession
4.  Copy the code from the Code Snippet box and paste it into the right-hand pane of Outlook's VB Editor window
5.  Edit the code as needed.  I included comment lines wherever something needs to or can change
6.  Click the diskette icon on the toolbar to save the changes
7.  Close the VB Editor
8.  Click Tools > Trust Center
9.  Click Macro Security
10. Set Macro Security to "Warnings for all macros"
11. Click OK
12. Close Outlook
13. Start Outlook.  Outlook will display a dialog-box warning that ThisOutlookSession contains macros and asking if you want to allow them to run.  Say yes.

Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
    Dim arrEID As Variant, varEid As Variant, olkMsg As Object
    arrEID = Split(EntryIDCollection, ",")
    For Each varEid In arrEID
        Set olkMsg = Session.GetItemFromID(varEid)
        If olkMsg.Class = olMail Then
            If UnwantedMessage(olkMsg) Then
                'On the next line change the name of the folder the unwanted messages will be move to.  That folder must be under the Inbox folder.
                olkMsg.Move Session.GetDefaultFolder(olFolderInbox).Folders("Unwanted")
            End If
        End If
    Next
    Set olkMsg = Nothing
End Sub

Function UnwantedMessage(olkMsg As Outlook.MailItem) As Boolean
    'On the next line edit the keywords/phrases you want to filter out.  Use the | character to separate each word/phrase
    Const KEYWORDS = "Out of Office Reply|Read:"
    Dim olkAtt As Outlook.Attachment, objRegEx As Object, colMatches As Object
    Set objRegEx = CreateObject("VBscript.RegExp")
    With objRegEx
        .IgnoreCase = False
        .Pattern = KEYWORDS
        .Global = True
    End With
    For Each olkAtt In olkMsg.Attachments
        If Not Prod_Support_Functions.IsHiddenAttachment(olkAtt) Then
            Set colMatches = objRegEx.Execute(olkAtt.Filename)
            If colMatches.Count > 0 Then
                UnwantedMessage = True
                Exit For
            End If
        End If
    Next
    Set olkAtt = Nothing
    Set objRegEx = Nothing
    Set colMatches = Nothing
End Function

Public Function IsHiddenAttachment(olkAtt As Outlook.Attachment) As Boolean
    ' Purpose: Determines if an attachment is a hidden attachment.
    ' Written: 7/12/2012
    ' Author:  David Lee
    ' Outlook: 2007 and later
    Const PR_ATTACH_CONTENT_ID = "http://schemas.microsoft.com/mapi/proptag/0x3712001E"
    Dim olkPA As Outlook.PropertyAccessor, varTemp As Variant
    On Error Resume Next
    Set olkPA = olkAtt.PropertyAccessor
    varTemp = olkPA.GetProperty(PR_ATTACH_CONTENT_ID)
    IsHiddenAttachment = (varTemp <> "")
    On Error GoTo 0
    Set olkPA = Nothing
End Function

Open in new window

I am using Outlook 2010

I get an error "Run-time error '424':

Object Required

When I click Debug it highlights this line of code:

"If Not Prod_Support_Functions.IsHiddenAttachment(olkAtt) Then"

I only made a change on the Keywords

Thanks,
Change

"If Not Prod_Support_Functions.IsHiddenAttachment(olkAtt) Then"

to

""If IsHiddenAttachment(olkAtt) Then"
ok I did and I am letting the macro run, no errors yet, but no emails are moved to the 'Unwanted' folder.

Thanks,

J
You created the Unwanted folder, right?
Yes 'Unwanted' folder, is this only going to work for new emails? No errors but nothing in the "Unwanted" folder...

I'll wait and let you know... I added more keywords
Yes, this is only going to work for new emails.
Ok I have three different mailboxes besides my primary one, I wanted to run the macro only on one of those three other mailboxes, could this be the problem that it is not finding anything? Because I have 4 mailboxes in one single Outlook profile?

I can create its own profile, but then I wont' be able to open my primary mailbox.

I have created its own profile, but still no results, again I will wait until tomorrow and let you know.

Do I have to have the Outlook profile open?

Thanks,

J
I checked this morning and no messages have been moved to the 'Unwanted' folder. How can  I run the macro and see if there is anything wrong with it?

Thanks,

J
Ok so you get a better idea of what I am trying to accomplish. I have attached a copy of the emails that I get into this inbox. All the emails I get are the same, with the exception of the attachment as you wil see.

This particular one has an email attached with a a word 'CID' in the Subject line which I want to use as a KEYWORD and move it to the 'Unwanted' folder.

I hope this helps you.

*This email has been cleaned from any other personal or private information, the return email address is public, but please do not share it or publish it without our consent*

Thanks again,

J
PlainText-Messages.msg
The macro isn't designed to be run manually.  It's triggered by items arriving in the mailbox.  The only way to test it is to send yourself a message with an attachment that meets the filter condition.  

To help figure out what's going on I've modified the code to display a dialog-box for every item received.  The dialog-box will show the subject of the message while the caption will say either "Unwanted Message" or "Wanted Message".  If no dialog-box shows, then either the code isn't running at all (macro security isn't set to allow macros to run) or the code is monitoring the wrong mailbox.

Please replace the code you have now with the version below and let me know what happens after you've received a few messages.

Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
    Dim arrEID As Variant, varEid As Variant, olkMsg As Object
    arrEID = Split(EntryIDCollection, ",")
    For Each varEid In arrEID
        Set olkMsg = Session.GetItemFromID(varEid)
        If olkMsg.Class = olMail Then
            If UnwantedMessage(olkMsg) Then
                'On the next line change the name of the folder the unwanted messages will be move to.  That folder must be under the Inbox folder.
                olkMsg.Move Session.GetDefaultFolder(olFolderInbox).Folders("Unwanted")
                MsgBox olkMsg.Subject, vbInformation+vbOkOnly, "Unwanted Message"
            Else
                MsgBox olkMsg.Subject, vbInformation+vbOkOnly, "Wanted Message"
            End If
        End If
    Next
    Set olkMsg = Nothing
End Sub

Function UnwantedMessage(olkMsg As Outlook.MailItem) As Boolean
    'On the next line edit the keywords/phrases you want to filter out.  Use the | character to separate each word/phrase
    Const KEYWORDS = "Out of Office Reply|Read:"
    Dim olkAtt As Outlook.Attachment, objRegEx As Object, colMatches As Object
    Set objRegEx = CreateObject("VBscript.RegExp")
    With objRegEx
        .IgnoreCase = False
        .Pattern = KEYWORDS
        .Global = True
    End With
    For Each olkAtt In olkMsg.Attachments
        If Not Prod_Support_Functions.IsHiddenAttachment(olkAtt) Then
            Set colMatches = objRegEx.Execute(olkAtt.Filename)
            If colMatches.Count > 0 Then
                UnwantedMessage = True
                Exit For
            End If
        End If
    Next
    Set olkAtt = Nothing
    Set objRegEx = Nothing
    Set colMatches = Nothing
End Function

Public Function IsHiddenAttachment(olkAtt As Outlook.Attachment) As Boolean
    ' Purpose: Determines if an attachment is a hidden attachment.
    ' Written: 7/12/2012
    ' Author:  David Lee
    ' Outlook: 2007 and later
    Const PR_ATTACH_CONTENT_ID = "http://schemas.microsoft.com/mapi/proptag/0x3712001E"
    Dim olkPA As Outlook.PropertyAccessor, varTemp As Variant
    On Error Resume Next
    Set olkPA = olkAtt.PropertyAccessor
    varTemp = olkPA.GetProperty(PR_ATTACH_CONTENT_ID)
    IsHiddenAttachment = (varTemp <> "")
    On Error GoTo 0
    Set olkPA = Nothing
End Function

Open in new window

Ok that is done and I am getting pop ups for Wanted Messages (see attachment) but nothing for Unwanted ones, I also have only one KEYWORD 'CID' and emails containing that keyword are coming in, but not filtered by the macro.

I also did this change in the code as it failed on this line.

"If Not Prod_Support_Functions.IsHiddenAttachment(olkAtt) Then"

to

""If IsHiddenAttachment(olkAtt) Then"


Thanks,

J
WantedMessagePopUp.png
is CID actually in the name of the attachment?  Can you post a screen shot so I can see what one of these messages with an unwanted attachment looks like?
ASKER CERTIFIED SOLUTION
Avatar of Jose Rivera-Hernandez
Jose Rivera-Hernandez
Flag of United States of America 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
I just ran a test and it looks like it's not even looking at the Subject lines because it skipped an email with the keyword "Automatic Reply:" see the image attached. The pop up was for Wanted message when it certainly the macro is supposed to flag it as Unwanted message.
Wantedmessage.jpg
The pop-up is showing the subject of the message so you can identify which message generated the popup.  It has nothing to do with what the code is checking.  

How about the screen-shot of one of the unwanted messages (i.e. the actual message window, not the popup the code is generating)?
sure here is one that came in a few minutes and there was no pop up although the Keyword was in it.

Thanks,

J
incomingemail.png
can we instead of sending them to the "Unwanted folder" send them to the Deleted Items bin? not sure if this is going to make it easier...

thanks,

J
Add this code to what you already have.  Select one of the unwanted message in your inbox and run this macro.  Let me know what happens.

Sub TestUM()
    MsgBox "This message is " & IIf(UnwantedMessage(Application.ActiveExplorer.Selection(1)), "unwanted", "wanted"), vbInformation + vbOKOnly, "Unwanted Message Test"
End Sub

Open in new window

ok I did that and the pop up stated that it was a Wanted message, see attachment.

Ok I have a proposition, why instead of looking at the Subject line, the macro looks at the "File Name", see the second screenshot, I am not sure if this would make it easier.

Thanks,

J
unanted.png
filena.png
The code IS looking at the file name.  Look at line #31 of the code.  

So you selected a message with an unwanted attachment, ran that macro, and got the popup saying it was wanted.  That's very odd.  I tested the code and it works perfectly.  How would you feel about forwarding one of the unwanted message to me so I can test the code against it?  Perhaps there's something different about my test message from the actual messages you're receiving.
Yes the screenshot shows the email I ran the macro against and its results.

use the attached email, the keyword I am looking for in this email is "CID"

Thanks,

J
PlainText-Messages.msg
unanted.png
Ok I made a change on the KEYWORDS and it seems to be working now

I changed "Automatic reply: "

to

"Automatic reply|CID|Out of Office AutoReply"

I am now getting the messages moved to the Unwanted folder.

I increased it to 400 points since you have been very patient and got this working, you saved me hours...


Thanks,

Jose
You're welcome, Jose.  Glad I could help.
Saved me hours with this script!!!