Send Messages with Zip File Attachments to Junk Mail


One of the things I do each morning is check Twitter for questions about Outlook. This morning I found this one from Meester Neek.

Someone else had already replied to the tweet suggesting that Meester Neek create a rule to handle this. Unfortunately, Outlook’s only rule condition for attachments is which has an attachment. There is no option for specifying an attachment name or type. We can still use a rule and that rule can use the which has an attachment condition, but the rule is going to have to run a script in order to determine if any of the attachments are zip files and act accordingly. The script itself is extremely simple. All it has to do is check the file name of each attachment to see if it ends with .zip. If it does, then the script will move the message to the Junk E-mail folder. Otherwise, the script does nothing. This solution should work for any version of Outlook on a PC. Note that it will not work for Outlook on a Mac, OWA, or mobile devices.

Instructions.

Follow these instructions to add the code to Outlook.

  1. Start Outlook
  2. Press ALT + F11 to open the Visual Basic Editor
  3. If not already expanded, expand Microsoft Office Outlook Objects
  4. If not already expanded, expand Modules
  5. Select an existing module (e.g. Module1) by double-clicking on it or create a new module by right-clicking Modules and selecting InsertModule.
  6. Copy the code from the code snippet box and paste it into the right-hand pane of Outlook’s VB Editor window
  7. Click the diskette icon on the toolbar to save the changes
  8. Close the VB Editor
Sub MoveZipFilesToJunk(Item As Outlook.MailItem)
    Dim olkAtt As Outlook.Attachment
    'Check each attachment
    For Each olkAtt In Item.Attachments
        'If the attachment's file name ends with .zip
        If Right(LCase(olkAtt.Filename), 4) = ".zip" Then
            'Move the message to Junk E-mail
            Item.Move Session.GetDefaultFolder(olFolderJunk)
            'No need to check any of this message's remaining attachments
            Exit For
        End If
    Next
    Set olkAtt = Nothing
End Sub

Creating the Rule.

  1. Create a new rule that fires each time a new message is received.
  2. Set the rule’s condition to which has an attachment.
  3. Set the rule’s action to run a script and select this script as the one to run.

71 comments on “Send Messages with Zip File Attachments to Junk Mail

  1. I can not move .gz to Junk Email

    Can you help me

    Sub MoveZipFilesToJunk(Item As Outlook.MailItem)
    Dim olkAtt As Outlook.Attachment
    ‘Check each attachment
    For Each olkAtt In Item.Attachments
    ‘If the attachment’s file name ends with .gz
    If Right(LCase(olkAtt.FileName), 3) = “.gz” Then
    ‘Move the message to Junk E-mail
    Item.Move Session.GetDefaultFolder(olFolderJunk)
    ‘No need to check any of this message’s remaining attachments
    Exit For
    End If
    Next
    Set olkAtt = Nothing
    End Sub

  2. Dear David Lee
    Great Thanks .

    I can not move .gz to junk email

    Can you help me ?
    THanks

    Sub MoveZipFilesToJunk(Item As Outlook.MailItem)
    Dim olkAtt As Outlook.Attachment
    ‘Check each attachment
    For Each olkAtt In Item.Attachments
    ‘If the attachment’s file name ends with .arj
    If Right(LCase(olkAtt.FileName), 3) = “.gz” Then
    ‘Move the message to Junk E-mail
    Item.Move Session.GetDefaultFolder(olFolderJunk)
    ‘No need to check any of this message’s remaining attachments
    Exit For
    End If
    Next
    Set olkAtt = Nothing
    End Sub

  3. I am trying to create a macro similar to this to help me with work. I get a bunch of emails from systems that all have a certain string in the subject line and they all have an attached file named PRINT01.TXT. This file is 1KB in size when everything goes right, and it is larger when something has gone wrong. I would like to set up a rule/macro combo that moves all emails with the PRINT01.TXT file attachment of 1KB or less to the deleted messages folder. I cannot seem to modify your code to make that work. Do you have any tips/advice?

    • Actually, never mind. I thoroughly read the comments below and realized my macros simply weren’t being run, rather than a problem with my code. I fixed that problem and was able to create the code to do the job I needed myself. See below. Feel free to correct or add commentary if there is anything I should have done differently. I had to play around with the file size I was checking for.

      Sub MoveGoodBAFiles(Item As Outlook.MailItem)
          Dim olkAtt As Outlook.Attachment
          'Check each attachment
          For Each olkAtt In Item.Attachments
              'If an attachment is named PRINT01.TXT
              If olkAtt.FileName = "PRINT01.TXT" Then
                  'A good PRINT01.TXT is 1KB in size. Check file size
                  If olkAtt.Size < "1324" Then
                      Item.Move Session.GetDefaultFolder(olFolderDeletedItems)
                  End If
                  'No need to check any of this message's remaining attachments
                  Exit For
              End If
          Next
          Set olkAtt = Nothing
      End Sub
      
    • Hi, Chris.

      Glad you got this working. Your version is fine. If you want to shorten the code a bit, then you could combine the two IF … THEN statements into a single statement. It’s also unnecessary to convert the attachment size to a string value. You can leave it as a number.

      Sub MoveGoodBAFiles(Item As Outlook.MailItem)
          Dim olkAtt As Outlook.Attachment
          'Check each attachment
          For Each olkAtt In Item.Attachments
              'If an attachment is named PRINT01.TXT and is 1KB in size
              If (olkAtt.FileName = "PRINT01.TXT") AND (olkAtt.Size < 1324) Then
                  Item.Move Session.GetDefaultFolder(olFolderDeletedItems)
                  'No need to check any of this message's remaining attachments
                  Exit For
              End If
          Next
          Set olkAtt = Nothing
      End Sub
      
  4. I successfully used the code and created a rule to move .zip attachments to the Junk E-mail folder, however I’d like to move more than .zip file extensions to a folder other than Junk E-mail such as Quarantine. What is the code to add additional file extensions and move to another folder? MS Outlook 2013 client. Thank you.

    • Hi, camp.

      This should do it. You can add as many file types as you want. I added ones for pdf and docx files. You can change or delete those as needed. To add additional extensions, simply duplicate the “Case” statement and the indented lines under it. You will need the path to the Outlook folder you want to move messages with that type of file attached to.

      Sub MoveFilesBasedOnExtension(Item As Outlook.MailItem)
          Dim olkAtt As Outlook.Attachment, objFSO As Object, strTyp As String
          Set objFSO = CreateObject("Scripting.FileSystemObject")
          'Check each attachment
          For Each olkAtt In Item.Attachments
              'Get the file type
              strTyp = LCase(objFSO.GetExtensionName(olkAtt.FileName))
              'Take action based on the file type
              Select Case strTyp
                  Case "zip"
                      'Move the message to Junk E-mail
                      Item.Move Session.GetDefaultFolder(olFolderJunk)
                      'No need to check any of this message's remaining attachments
                      Exit For
                  Case "pdf"
                      'One the next line, edit the path to the folder you want to move the message to
                      Item.Move OpenOutlookFolder("path to some folder")
                      'No need to check any of this message's remaining attachments
                      Exit For
                  Case "docx"
                      'One the next line, edit the path to the folder you want to move the message to
                      Item.Move OpenOutlookFolder("path to some folder")
                      'No need to check any of this message's remaining attachments
                      Exit For
              End Select
          Next
          Set olkAtt = Nothing
          Set objFSO = Nothing
      End Sub
      
      Private Function OpenOutlookFolder(strFolderPath As String) As Outlook.MAPIFolder
          ' Purpose: Opens an Outlook folder from a folder path.'
          ' Written: 4/24/2009'
          ' Author:  BlueDevilFan'
          ' Outlook: All versions'
          Dim arrFolders As Variant, _
              varFolder As Variant, _
              bolBeyondRoot As Boolean
          On Error Resume Next
          If strFolderPath = "" Then
              Set OpenOutlookFolder = Nothing
          Else
              Do While Left(strFolderPath, 1) = "\"
                  strFolderPath = Right(strFolderPath, Len(strFolderPath) - 1)
              Loop
              arrFolders = Split(strFolderPath, "\")
              For Each varFolder In arrFolders
                  Select Case bolBeyondRoot
                      Case False
                          Set OpenOutlookFolder = Outlook.Session.Folders(varFolder)
                          bolBeyondRoot = True
                      Case True
                          Set OpenOutlookFolder = OpenOutlookFolder.Folders(varFolder)
                  End Select
                  If Err.Number <> 0 Then
                      Set OpenOutlookFolder = Nothing
                      Exit For
                  End If
              Next
          End If
          On Error GoTo 0
      End Function
      
  5. Hi there – I’ve set up the script in VBA editor but when I come to setting up the rule, there is simply NO option in the actions stage to ‘run a script’.

    I’ve scoured the internet and people seem to have problems selecting their script from the list under ‘run a script’, but my problem seems to be unique. There is literally no option to run a script.

    I’ve checked my macro settings to ‘Notifications for all macros’. I’m using Outlook 2016 – and have just checked Outlook 2010 which DOES have the option, so is this something Microsoft has removed entirely for Outlook2016, or can I turn it back on again somehow?

  6. Thanks for a great piece of code. Took me a bit to figure out how to enable macros, but it now works perfectly. I altered line 5 because I’m not getting .docm files with viruses.

    If Right(LCase(olkAtt.FileName), 4) = “.zip” Or Right(LCase(olkAtt.FileName), 5) = “.docm” Then

  7. Hi David. Thank you for the script! It worked great for a day and blocked a tons of emails with .zip files but the next day they’re all getting through again. It’s strange because I double checked the rules and script and everything looks intact. Would you have any idea why it stopped working after a day?

    • Hi, Eric.

      I don’t know. Here are some things to check.

      1. Are macros enabled?
      2. Is the rule firing?
      3. Do the messages meet the criteria specified in the rule?
    • hi quick question – I want to create rules in outlook that categorize emails by attachment type for word, pdf, excel and powerpoint. I think I need VBA to do that. What you have provided here for zip files seems to have the required logic but I dont know enough about VBA syntax to modify it to create catagories instead of deleting items.

    • Hi, Jonathan.

      This should do it. Don’t forget to edit the category names in the code.

      To use this, create a rule that fires for any message with an attachment. Set the rule’s action to “run a script” and select this script as the one to run.

      Sub CategorizeByAttachmentType(Item As Outlook.MailItem)
          Dim olkAtt As Outlook.Attachment
          'Check each attachment
          For Each olkAtt In Item.Attachments
              Select Case Right(LCase(olkAtt.FileName), 4)
                  Case ".pdf"
                      Item.Categories = "Category for PDF files"
                  Case ".xls", "xlsx", "xlsm"
                      Item.Categories = "Category for Excel files"
                  Case ".doc", "docx"
                      Item.Categories = "Category for Word files"
                  Case ".ppt", "pptx", "ppts"
                      Item.Categories = "Category for PowerPoint files            "
              End Select
          Next
          Item.Save
          Set olkAtt = Nothing
      End Sub
      
  8. Hi, thanks for the great code. Outlook is lacking in certain filters that I think are desperately needed these days.

    I use Outlook 2010 with IMAP. Is there a way to specifically move items into an IMAP folder? I tried some of those previous commands posted and it moved the items into my local “Archive” folder.

    Also, is there a way to filter the items based on the previous list of people I’ve sent email to? They’re not in my Contacts, that’s empty. But when I create a new email and just press the letter of the person their “name ” fills in.

    I’m trying to filter out .DOC & .XLS spam I’m getting, but would still like to receive those files in my Inbox from the people I send email to occasionally.

    • Hi, Tom.

      I am admittedly weak on Outlook and IMAP. Assuming that an IMAP folder appears to Outlook as a folder, then a script should be able to move a message to it. Or you could just have the script delete the message if it contains a .doc or .xls attachment unless it’s from someone you know. That list of people you correspond with should be in the Suggested Contacts folder. That’s list the script would check against.

  9. Hi David,

    I work in an environment where any emails containing a “.zip” attachment are junk and I would never have to save the email and check it to make sure it’s good because in my business we never send zip attachments. How would this rule need to be modified to automatically permanently delete (not send to junk mail) any messages that contain zip attachments on arrival? Thanks very much for your time!

    • Hi, Justin.

      The code below is a modified version of my original post that permanently deletes any message with a .zip file attached. Follow the instructions from the original post to add this code to Outlook. When creating the rule, use “PermanentlyDeleteMessagesWithZipFiles” instead of “MoveZipFilesToJunk” as the name of the script to run.

      Sub PermanentlyDeleteMessagesWithZipFiles(Item As Outlook.MailItem)
          Dim olkAtt As Outlook.Attachment, olkTmp As Outlook.MailItem
          'Check each attachment
          For Each olkAtt In Item.Attachments
              'If the attachment's file name ends with .zip
              If Right(LCase(olkAtt.FILENAME), 4) = ".zip" Then
                  'Move the message to Deleted Items
                  Set olkTmp = Item.Move(Session.GetDefaultFolder(olFolderDeletedItems))
                  'Delete the item just moved to Deleted Items
                  Set olkTmp = Session.GetItemFromID(olkTmp.EntryID)
                  olkTmp.Delete
                  'No need to check any of this message's remaining attachments
                  Exit For
              End If
          Next
          Set olkTmp = Nothing
          Set olkAtt = Nothing
      End Sub
      
  10. Hello David,
    I receive many emails from “Personx@xyz.com” in work. I want to put those emails from “Personx@xyz.com” into an inbox subfolder “Personx”; however, I only want to put them in the “Personx” subfolder if and only if they have a word document attached “.doc”. This is because when they arrive with a “.doc” attachment then I must immediately log them and start my process flows. Again, I receive many emails and I even get many emails from Personx (with and without) attachments; however, when they have a “.doc” attachment I must act immediately.
    I created a rule which has checked “With an attachment”, “from Personx”, “run a script” (using with your script making appropriate changes). This yielded no movement. When checked “move to a specified folder of Personx” then all emails from Personx moved into the folder.
    Any comments?
    Thanks,
    Joe

    • Hi, Joe.

      Can you share the changes you made to the script? It’s possible that there some simple problem that I can fix quickly.

    • Sub MoveDocFilesToCRiess(Item As Outlook.MailItem)
          Dim olkAtt As Outlook.Attachment
          'Check each attachment
          For Each olkAtt In Item.Attachments
              'If the attachment's file name ends with .doc
              If Right(LCase(olkAtt.FileName), 4) = ".doc" Then
                  'Move the message to Criess
                  Item.Move Session.GetDefaultFolder(olFolderCRiess)
                  'No need to check any of this message's remaining attachments
                  Exit For
              End If
          Next
          Set olkAtt = Nothing
      End Sub
      
    • Joe,

      This line of code is the problem.

      Item.Move Session.GetDefaultFolder(olFolderCRiess)
      

      The GetDefaultFolder method returns the default folder specified by the argument passed to it. The argument has to be a numeric value or a constant defining a numeric value. The value itself must match one of the values defined by the OlDefaultFolders enumeration (see this page for details). olFolderCRiess is not one of the predefined olDefaultFolder constants and in this case would not contain a numeric value. That’s why it isn’t working.

      The solution is simple. Change that line to

      Item.Move Session.GetDefaultFolder(olFolderInbox).Folders("CRiess")
      
    • David,
      The proper rules settings would be:
      Check “which has an attachment”
      Check “from people or public group” => properly specifying CRiess’s email address
      Check “run a script” => properly specifying this script
      but d I also check “move it to a specified folder” or is this script supposed to do that?
      Thanks,
      Joe

    • Joe,

      The rule doesn’t have to check for an attachment since the script is already doing that. It’s okay if it does, but it doesn’t have to. The script moves the item to the folder if the conditions are met, so do not set the rule to move the item to a folder. If you do, then the rule will move the item to the folder without regard to anything in the script. In other words, it will move every item matching the rule’s conditions to the folder even if the attachment is not a .doc file.

    • David,
      Not working for me. I have checked and double checked. am using Outlook 2013 on Windows 8.1. As I am 1000% new to Visual Basic not sure where I could be going wrong. I will try your original post (.doc instead of .zip) to be sure that VB is even working on my system.
      Thanks,
      Joe

    • David,
      My Macro setting has checked:
      Notifications for digitally signed macros, all other macros disabled.
      Thanks,
      Joe

    • Joe,

      Then unless you’ve signed this macro it isn’t going to be able to run. If you haven’t signed it, then your choices are to sign it, or change the macro security setting to either “Notifications for all macros” or “Enable all macros”.

    • David,
      For now I set Enable All Macros. What I am doing is creating the rule and then I try to run the rule. I leave a file from personx with a word doc attached (type .doc) in my inbox folder. It is not moving it. It can be run on emails already in my inbox correct – if I select run rule.
      FYI, when I view Rules and Alerts, the rule shows up but there is no icon under action column. Usually, for example, I would see a little folder with curved arrow indicating that the rule moves items to a different folder.
      Thanks,
      Joe

    • David,
      I enabled all macros for now. Not working. I should be able run the rule on my inbox correct? In other words, I left a file in the inbox that the routine should be moving but it isn’t moving. Selected manage rules and alerts – run this rule – selected the rule – run in folder “inbox” – apply rule to: All Messages – Run Now. Another question, should I be able to find VBAProject.OTM on my disk?

    • David,
      Is this command supposed to move the item or copy the item? In my case, it seems to be copying the item.
      Thanks,
      Joe

    • David,
      Forget that last post. It is moving the emails – just as expected.
      Thanks a lot – you’re the greatest.
      I now know very little VB and how to connect it with Outlook – very little but, just the same very helpful.
      Thanks again,
      Joe

  11. Pingback: Outlook Zip Files | OutlookRecoveryGuide.org

  12. This is great, thanks very much for that. In my case, I have been getting a lot of spam with attachments ending in “.zip.txt” – there is no situation where anyone would legitimately send me an attachment with this naming convention (we got dropbox for zipfiles!) so I modified the script to catch those, works like a charm.

    It’s a straightforward edit but here it is for anyone else inundated with similar irritating emails:

    Sub MoveZipTxtFilesToJunk(Item As Outlook.MailItem)
        Dim olkAtt As Outlook.Attachment
        'Check each attachment
        For Each olkAtt In Item.Attachments
            'If the attachment's file name ends with .zip.txt
            If Right(LCase(olkAtt.FileName), 8) = ".zip.txt" Then
                'Move the message to Junk E-mail
                Item.Move Session.GetDefaultFolder(olFolderJunk)
                'No need to check any of this message's remaining attachments
                Exit For
            End If
        Next
        Set olkAtt = Nothing
    End Sub
    

    Thanks again.

    • Hi, Beardy.

      You’re welcome. I’m glad the code was useful. Thank you for sharing your modification.

      Cheers!

  13. For some reason this isn’t working in my 2007 Outlook. I have tried making this my only rule and changed my Trust Center settings to no security checks for macros just to see if it would work, but no luck yet. Do you have any thoughts on what else I should look into to make this macro work?

    • Hi, Kathryn.

      Sometimes Outlook acts like macros aren’t enabled even after you’ve enabled them in the Trust Center. Try adding this code to the ThisOutlookSession module. Once you’ve added the code, close and re-start Outlook. When you do, you should see a pop-up telling you that macros are enabled. If the popup appears, then test the solution again and let me know if it’s working.

      Private Sub Application_Startup()
          MsgBox "Macros are enabled"
      End Sub
      
  14. Hi David,

    Great script, thank you. Can the script modified to move a ‘named’ zip file? I don’t want all the zip attachments sent to Junk. I want only attachments that has a name ‘Receipt.zip’ . Can you help please?

    • Hi, Faruky.

      You’re welcome!

      Sure. This version will only move messages with a attachment named “receipt.zip” to Outlook’s Junk folder.

      Sub MoveZipFilesToJunk(Item As Outlook.MailItem)
          Dim olkAtt As Outlook.Attachment
          'Check each attachment
          For Each olkAtt In Item.Attachments
              'If the attachment's file name ends with .zip
              If Right(LCase(olkAtt.Filename), 11) = "receipt.zip" Then
                  'Move the message to Junk E-mail
                  Item.Move Session.GetDefaultFolder(olFolderJunk)
                  'No need to check any of this message's remaining attachments
                  Exit For
              End If
          Next
          Set olkAtt = Nothing
      End Sub
      
    • Ok after trying it deletes all the files in the inbox. Have no idea why. I have two other rules. 1. move to deleted – subject kine
      2. Clear categories on mail…I did not put this there. It was already there.

      Any ideas?

    • Disable those two rules and see what happens. The macro doesn’t move anything to Deleted Items, so it can’t be responsible.

  15. Thank you – works perfectly.

    With the recent threat of Cryptolocker et al arriving by a zip attachment I would like to direct them straight to the deleted folder (which then deletes on exit of Outlook). I assume line 8 would need to be changed – but I’m not sure what it should be.

    Could you please advise?

    Thank you.

    • Hi, cmulder.

      While I understand that this isn’t working for you, the solution does work in Outlook 2010. Are macros enabled in Outlook on your computer? If not, that would explain why the solution isn’t working for you.

  16. The rule that seems to be on by default is “Clear Categories on Mail (recommended)”. I think it might be built in to Outlook 2010. I’ve removed that rule from a couple of users’ PCs and now the script seems to be running ok, but I didn’t try changing the order: I’ll set yours to run first from now on.

    Thanks & regards,
    Nick

    • Meester Neek,

      Unless that rule included the command to stop processing rules, I don’t know why it would be a problem. Glad you worked it out though.

  17. This solution was much appreciated, but for some reason it only seems to work when it is the only rule running on a particular PC. If there are any other rules, nothing seems to happen and zip file still land in the inbox. Any thoughts why this might be?

    • Hi, Meester Neek.

      I’d have to know more about the other rules, what they do, and what order the rules are running in. Rules are executed in the order they appear in in the “Rules and Alerts” dialog-box. If any of the other rules run before this rule and do something like move the message or halt rule processing, then this rule won’t get a chance to run against that message. On the other hand, if this is the first rule in line and isn’t working when there are other rules, then clearly something is wrong.

Leave a reply to Justin LeBlanc Cancel reply