• Outlook User
  • New Outlook app
  • Outlook.com
  • Outlook Mac
  • Outlook & iCloud
  • Developer
  • Microsoft 365 Admin
    • Common Problems
    • Microsoft 365
    • Outlook BCM
    • Utilities & Addins

Save and Delete Attachments from Outlook messages

Slipstick Systems

› Developer › Code Samples › Save and Delete Attachments from Outlook messages

Last reviewed on July 18, 2018     126 Comments

The following is the Save Attachment code sample from Teach Yourself Outlook 2003 in 24 Hours. (It works in current versions.)

Frank modified the code to break it into a single call for each mail item so you can use it with a rule to filter incoming mail. Augusto modified Frank's code "in order to avoid file overwriting when the attachment name is the same as an existing one (i.e. details.txt on a return receipt email). Now, the attachments are saved in the format “SenderName.ReceivedDate.filename.ext” and then the attachment is deleted from the original email." Augusto's code modification. There is also a version that deletes all attachments in the selected folder.

To use, first create a folder under your My Documents named OLAttachments. Then select one or more messages and run the macro to save and remove the attachments. (May wish to comment out the line that deletes the attachment before testing). Remove or comment out the MsgBox lines after testing.

To delete the attachments without saving them, leave just these lines between the If... and End if. (The macro can also be edited to remove the statements above the If command that are no longer needed.)

If lngCount > 0 Then
 For i = lngCountb To 1 Step -1
 
 ' Delete the attachment.
 objAttachments.Item(i).Delete
 
 Next i
 objMsg.Save
 
 End If

Copy and paste the code from this page into your ThisOutlookSession project. To do this, you can either move your mouse to the right of the first line and click the Copy button (or view source code button then select all, copy and paste). Or copy it from this text file: Save and Delete Attachments. After pasting the code into the VB Editor, it should be colored similar to the code below. A Red line indicates problems with the line.

In Outlook, press Alt+F11 to open the VBA editor and expand Microsoft Outlook Objects then double click on ThisOutlookSession to open it in the editing pane and Ctrl+V to paste the code.

Public Sub SaveAttachments()
 Dim objOL As Outlook.Application
 Dim objMsg As Outlook.MailItem 'Object
 Dim objAttachments As Outlook.Attachments
 Dim objSelection As Outlook.Selection
 Dim i As Long
 Dim lngCount As Long
 Dim strFile As String
 Dim strFolderpath As String
 Dim strDeletedFiles As String

    ' Get the path to your My Documents folder
    strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
    On Error Resume Next

     ' Instantiate an Outlook Application object.
     Set objOL = CreateObject("Outlook.Application")

     ' Get the collection of selected objects.
     Set objSelection = objOL.ActiveExplorer.Selection

     ' Set the Attachment folder.
     strFolderpath = strFolderpath & "OLAttachments"

     'Use the MsgBox command to troubleshoot. Remove it from the final code.
     MsgBox strFolderpath
 
     ' Check each selected item for attachments. If attachments exist,
     ' save them to the Temp folder and strip them from the item.
     For Each objMsg In objSelection

     ' This code only strips attachments from mail items.
     ' If objMsg.class=olMail Then
     ' Get the Attachments collection of the item.
     Set objAttachments = objMsg.Attachments
     lngCount = objAttachments.Count

     'Use the MsgBox command to troubleshoot. Remove it from the final code.
     MsgBox objAttachments.Count

     If lngCount > 0 Then

     ' We need to use a count down loop for removing items
     ' from a collection. Otherwise, the loop counter gets
     ' confused and only every other item is removed.
     
     For i = lngCount To 1 Step -1
     
     ' Save attachment before deleting from item.
     ' Get the file name.
     strFile = objAttachments.Item(i).FileName
     
     ' Combine with the path to the Temp folder.
     strFile = strFolderpath & strFile
     
     ' Save the attachment as a file.
     objAttachments.Item(i).SaveAsFile strFile
     
     ' Delete the attachment.
     objAttachments.Item(i).Delete
     
     'write the save as path to a string to add to the message
     'check for html and use html tags in link
     If objMsg.BodyFormat <> olFormatHTML Then
         strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
         Else
         strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _ strFile & "'>" & strFile & "</a>"
     End If
     
     'Use the MsgBox command to troubleshoot. Remove it from the final code.
     MsgBox strDeletedFiles
     
     Next i
     'End If
     
     ' Adds the filename string to the message body and save it
     ' Check for HTML body
     If objMsg.BodyFormat <> olFormatHTML Then
         objMsg.Body = objMsg.Body & vbCrLf & _
         "The file(s) were saved to " & strDeletedFiles
     Else
         objMsg.HTMLBody = objMsg.HTMLBody & "</p> <p>" & _
         "The file(s) were saved to " & strDeletedFiles & "</p> <p>"
     End If
         objMsg.Save
 'sets the attachment path to nothing before it moves on to the next message. 
         strDeletedFiles = ""
 
     End If
     Next
     
 ExitSub:
 
 Set objAttachments = Nothing
 Set objMsg = Nothing
 Set objSelection = Nothing
 Set objOL = Nothing
 End Sub 

Frank's Modification

Frank modified the structure to break the code into a single call for each mail item. This way, the code can be used for all items selected, but at the same time a RULE can invoke the code also when incoming mail hits the box. here’s the modification.

Public Sub SaveAttachments()
    Dim objOL As Outlook.Application
    Dim pobjMsg As Outlook.MailItem 'Object
    Dim objSelection As Outlook.Selection

    ' Get the path to your My Documents folder
    strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
    On Error Resume Next

    ' Instantiate an Outlook Application object.
    Set objOL = CreateObject("Outlook.Application")

    ' Get the collection of selected objects.
    Set objSelection = objOL.ActiveExplorer.Selection

    For Each pobjMsg In objSelection
        SaveAttachments_Parameter pobjMsg
    Next

ExitSub:

    Set pobjMsg = Nothing
    Set objSelection = Nothing
    Set objOL = Nothing
End Sub

Public Sub SaveAttachments_Parameter(objMsg As MailItem)
    Dim objAttachments As Outlook.Attachments
    Dim i As Long
    Dim lngCount As Long
    Dim strFile As String
    Dim strFolderpath As String
    Dim strDeletedFiles As String

    ' Get the path to your My Documents folder
    strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
    On Error Resume Next

    ' Set the Attachment folder.
    strFolderpath = strFolderpath & "OLAttachments"

        ' Get the Attachments collection of the item.
        Set objAttachments = objMsg.Attachments
        lngCount = objAttachments.Count

        If lngCount > 0 Then

            ' We need to use a count down loop for removing items
            ' from a collection. Otherwise, the loop counter gets
            ' confused and only every other item is removed.
            For i = lngCount To 1 Step -1

                ' Save attachment before deleting from item.
                ' Get the file name.
                strFile = objAttachments.Item(i).FileName

                ' Combine with the path to the Temp folder.
                strFile = strFolderpath & strFile

                ' Save the attachment as a file.
                objAttachments.Item(i).SaveAsFile strFile

                ' Delete the attachment.
                'objAttachments.Item(i).Delete

                'write the save as path to a string to add to the message
                'check for html and use html tags in link
                If objMsg.BodyFormat  olFormatHTML Then
                   strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & strFile & "'>" & strFile & "</a>"
                  Else
                   strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
                End If
            Next i
        End If

        ' Adds the filename string to the message body and save it [COMMENTED AS THIS FUNCTION WAS NOT DESIRED]
        ' Check for HTML body
        '        If objMsg.BodyFormat  olFormatHTML Then
        '            objMsg.Body = objMsg.Body & vbCrLf & _
        '            "The file(s) were saved to " & strDeletedFiles
        '        Else
        '            objMsg.HTMLBody = objMsg.HTMLBody & "" & _
        '            "The file(s) were saved to " & strDeletedFiles & ""
        '        End If
        objMsg.Save
ExitSub:

    Set objAttachments = Nothing
    Set objMsg = Nothing
    Set objOL = Nothing
End Sub

Augusto's Modification


Augusto
made some modifications on Frank’s code, in order to avoid file overwriting when the attachment name is the same as an existing one (i.e. details.txt on a return receipt email). Now, the attachments are saved in the format “SenderName.ReceivedDate.filename.ext” and then the attachment is deleted from the original email.

Here is Augusto's code:

Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim pobjMsg As Outlook.MailItem 'Object
Dim objSelection As Outlook.Selection
 
' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next
 
' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")
 
' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection
 
For Each pobjMsg In objSelection
SaveAttachments_Parameter pobjMsg
Next
 
ExitSub:
 
Set pobjMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub
 
Public Sub SaveAttachments_Parameter(objMsg As MailItem)
Dim objAttachments As Outlook.Attachments
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String
 
' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next
 
' Set the Attachment folder.
strFolderpath = strFolderpath & "\OLAttachments\"
 
' Get the Attachments collection of the item.
Set objAttachments = objMsg.Attachments
lngCount = objAttachments.Count
 
If lngCount > 0 Then
 
' We need to use a count down loop for removing items
' from a collection. Otherwise, the loop counter gets
' confused and only every other item is removed.
For i = lngCount To 1 Step -1
 
' Save attachment before deleting from item.
' Get the file name.
strFile = objAttachments.Item(i).FileName
 
' Combine with the path to the Temp folder.
strFile = strFolderpath & objMsg.SenderName & "." & Format(objMsg.ReceivedTime, "yyyy-MM-dd h-mm-ss") & "." & strFile
 
' Save the attachment as a file.
objAttachments.Item(i).SaveAsFile strFile
 
' Delete the attachment.
objAttachments.Item(i).Delete
 
'write the save as path to a string to add to the message
'check for html and use html tags in link
If objMsg.BodyFormat olFormatHTML Then
                   strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & strFile & "'>" & strFile & "</a>"
                  Else
                   strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
End If
Next i
End If
 
' Adds the filename string to the message body and save it
' Check for HTML body
If objMsg.BodyFormat olFormatHTML Then
objMsg.Body = objMsg.Body & vbCrLf & _
"The file(s) were saved to " & strDeletedFiles
Else
objMsg.HTMLBody = objMsg.HTMLBody & "" & _
"The file(s) were saved to " & strDeletedFiles & ""
End If
objMsg.Save
ExitSub:
 
Set objAttachments = Nothing
Set objMsg = Nothing
Set objOL = Nothing
End Sub

Delete all attachments in the selected folder

Select a folder and run this code to process all messages in the current folder. The "magic" in this code is using the CurrentFolder object: Set Mail = objOL.ActiveExplorer.CurrentFolder instead of the Selection object.

Public Sub SaveDeleteAttachments()
 
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String

    strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
    On Error Resume Next
    strFolderpath = strFolderpath & "OLAttachments"

    Set objOL = CreateObject("Outlook.Application")
    Set Mail = objOL.ActiveExplorer.CurrentFolder
  
    For Each objMsg In Mail.Items

    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count

    If lngCount > 0 Then

    For i = lngCount To 1 Step -1

    strFile = objAttachments.Item(i).FileName
    strFile = strFolderpath & strFile

    objAttachments.Item(i).SaveAsFile strFile
    objAttachments.Item(i).Delete

    If objMsg.BodyFormat <> olFormatHTML Then
        strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
        Else
        strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
        strFile & "'>" & strFile & "</a>"
    End If
  
    Next i
    'End If

    If objMsg.BodyFormat <> olFormatHTML Then
        objMsg.Body = objMsg.Body & vbCrLf & _
        "The file(s) were saved to " & strDeletedFiles
    Else
        objMsg.HTMLBody = objMsg.HTMLBody & "<p>" & _
        "The file(s) were saved to " & strDeletedFiles & "</p>"
    End If
        objMsg.Save
        strDeletedFiles = ""

    End If
    Next

ExitSub:

Set objAttachments = Nothing
Set objMsg = Nothing
Set objOL = Nothing
End Sub

Save and Delete Attachments from Outlook messages was last modified: July 18th, 2018 by Diane Poremsky

Related Posts:

  • Save Messages and Attachments to a New Folder
  • Browseforfolder_2
    How to use Windows File Paths in a Macro
  • Save and Open an Attachment using VBA
  • Save Attachments to the Hard Drive

About Diane Poremsky

A Microsoft Outlook Most Valuable Professional (MVP) since 1999, Diane is the author of several books, including Outlook 2013 Absolute Beginners Book. She also created video training CDs and online training classes for Microsoft Outlook. You can find her helping people online in Outlook Forums as well as in the Microsoft Answers and TechNet forums.

Subscribe
Notify of
126 Comments
newest
oldest most voted
Inline Feedbacks
View all comments

Andy M
December 16, 2021 1:53 pm

Do you have a solution for preserving links to folders with spaces in their names? I tried to bracket the link with "<" and ">" like I would if I were writing an email, but it ends up erasing the link altogether...

0
0
Reply
Diane Poremsky
Author
Reply to  Andy M
December 16, 2021 10:56 pm

Try replacing the spaces with %20. Yes, its ugly, but should definitely work if brackets and quotes around the folder name doesn't work.

0
0
Reply
Claudia
January 13, 2021 11:20 am

ok, I have found a way to avoid that embedded signature pictures (mostly png) are getting deleted. There was a hint far down in the comments: only save/delete certain file types:
look for the line strFile = objAttachments.Item(i).FileName
Add this under

sFileType = LCase$(Right$(strFile, 4))

   Select Case sFileType
       Case ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".zip"
   ' only if the file types are found - you can add more

Now look for the line 'write the save as path to a string to add to the message
Add this behind the first End If


End Select
' end selection file types are found

This works very good ;-)

0
0
Reply
Claudia
January 5, 2021 11:23 am

Hi, these macro codes are really helpfull, I use a mix especially with augustos code : delete attachments from selected mails one without saving, one with and deletion info at top of the mail without links only text,
but one thing is still missing and wasn't asked yet:

  • how can I change the code to only delete attachments which are NOT Embedded "hidden" like signature pictures?

Is there a way to exclude those?

Thanks in Advance ;-)

0
0
Reply
Richard
October 22, 2020 12:02 pm

A user has sent out 150+ individual emails with an attached word doc containing un-compressed images (so the word doc is 8.8Mb) but there are other attachments to each email we need to retain.

So if anyone can provide a script to remove just a specific attachment e.g letter.docx from all emails in the Sent Item folder, it would be a huge help.

1
0
Reply
Sos
September 5, 2020 3:54 am

HI im not a programmer, so i dont undetrstand much of what you are saying could you give me a script for deleting inbox attachments with file type??

1
0
Reply
Patrick Tingen
July 1, 2020 5:47 am

I receive emails with email inside. I need the attachments that are inside that embedded email. What should I change to get this to work?

0
0
Reply
Ben
June 18, 2020 1:59 am

Is it possible to have the file path links posted in the email thread appear at the very top instead of at the bottom?

1
0
Reply
Diane Poremsky
Author
Reply to  Ben
June 18, 2020 4:42 pm

Sure. Just change the order in the code:

 If objMsg.BodyFormat <> olFormatHTML Then
         objMsg.Body = objMsg.Body & vbCrLf & _
         "The file(s) were saved to " & strDeletedFiles
     Else
         objMsg.HTMLBody = objMsg.HTMLBody & "</p> <p>" & _
         "The file(s) were saved to " & strDeletedFiles & "</p> <p>"
     End If

 If objMsg.BodyFormat <> olFormatHTML Then
         objMsg.Body = "The file(s) were saved to " & strDeletedFiles  & vbCrLf & _
         objMsg.Body
     Else
' i think this is right - i did not test. The  html p's add a little complexity. 
         objMsg.HTMLBody =  "<p> The file(s) were saved to " & strDeletedFiles" & _
         "</p>" &  objMsg.HTMLBody
     End If

0
0
Reply
Ben
Reply to  Diane Poremsky
June 18, 2020 4:53 pm

It worked flawlessly. Thank you very much for this. What an incredibly powerful tool!

0
0
Reply
Paul
May 28, 2020 5:01 pm

I'm using the Selected Folder code but am getting the following error when stepping through the code. "objMsg.Body = " Application-defined or object-defined error
and nothing is being written to the email body. Email is in Text format (objMsg.BodyFormat =1).
Thanks.

0
0
Reply

Visit Slipstick Forums.
What's New at Slipstick.com

Latest EMO: Vol. 30 Issue 36

Subscribe to Exchange Messaging Outlook






Support Services

Do you need help setting up Outlook, moving your email to a new computer, migrating or configuring Office 365, or just need some one-on-one assistance?

Our Sponsors

CompanionLink
ReliefJet
  • Popular
  • Latest
  • Week Month All
  • Use Classic Outlook, not New Outlook
  • How to Remove the Primary Account from Outlook
  • Reset the New Outlook Profile
  • Adjusting Outlook's Zoom Setting in Email
  • How to Hide or Delete Outlook's Default Folders
  • Removing Suggested Accounts in New Outlook
  • OUTLOOK.EXE continues running after you exit Outlook
  • Shared Mailboxes and the Default 'Send From' Account
  • This operation has been cancelled due to restrictions
  • Add Holidays to Outlook's Calendar
  • Opt out of Microsoft 365 Companion Apps
  • Mail Templates in Outlook for Windows (and Web)
  • Urban legend: Microsoft Deletes Old Outlook.com Messages
  • Buttons in the New Message Notifications
  • Move Deleted Items to Another Folder Automatically
  • Open Outlook Templates using PowerShell
  • Count and List Folders in Classic Outlook
  • Google Workspace and Outlook with POP Mail
  • Import EML Files into New Outlook
  • Opening PST files in New Outlook
Ajax spinner

Recent Bugs List

Microsoft keeps a running list of issues affecting recently released updates at Fixes or workarounds for recent issues in classic Outlook (Windows).

For new Outlook for Windows: Fixes or workarounds for recent issues in new Outlook for Windows .

Outlook for Mac Recent issues: Fixes or workarounds for recent issues in Outlook for Mac

Outlook.com Recent issues: Fixes or workarounds for recent issues on Outlook.com

Office Update History

Update history for supported Office versions is at Update history for Office

Outlook Suggestions and Feedback

Outlook Feedback covers Outlook as an email client, including Outlook Android, iOS, Mac, and Windows clients, as well as the browser extension (PWA) and Outlook on the web.

Outlook (new) Feedback. Use this for feedback and suggestions for Outlook (new).

Use Outlook.com Feedback for suggestions or feedback about Outlook.com accounts.

Other Microsoft 365 applications and services




New Outlook Articles

Opt out of Microsoft 365 Companion Apps

Mail Templates in Outlook for Windows (and Web)

Urban legend: Microsoft Deletes Old Outlook.com Messages

Buttons in the New Message Notifications

Move Deleted Items to Another Folder Automatically

Open Outlook Templates using PowerShell

Count and List Folders in Classic Outlook

Google Workspace and Outlook with POP Mail

Import EML Files into New Outlook

Opening PST files in New Outlook

Newest Code Samples

Open Outlook Templates using PowerShell

Count and List Folders in Classic Outlook

Insert Word Document into Email using VBA

Warn Before Deleting a Contact

Use PowerShell to Delete Attachments

Remove RE:, FWD:, and Other Prefixes from Subject Line

Change the Mailing Address Using PowerShell

Categorize @Mentioned Messages

Send an Email When You Open Outlook

Delete Old Calendar Events using VBA

VBA Basics

How to use the VBA Editor

Work with open item or selected item

Working with All Items in a Folder or Selected Items

VBA and non-default Outlook Folders

Backup and save your Outlook VBA macros

Get text using Left, Right, Mid, Len, InStr

Using Arrays in Outlook macros

Use RegEx to extract message text

Paste clipboard contents

Windows Folder Picker

Custom Forms

Designing Microsoft Outlook Forms

Set a custom form as default

Developer Resources

Developer Resources

Developer Tools

VBOffice.net samples

SlovakTech.com

Outlook MVP David Lee

Repair PST

Convert an OST to PST

Repair damaged PST file

Repair large PST File

Remove password from PST

Merge Two Data Files

Sync & Share Outlook Data

  • Share Calendar & Contacts
  • Synchronize two computers
  • Sync Calendar and Contacts Using Outlook.com
  • Sync Outlook & Android Devices
  • Sync Google Calendar with Outlook
  • Access Folders in Other Users Mailboxes

Diane Poremsky [Outlook MVP]

Make a donation

Mail Tools

Sending and Retrieval Tools

Mass Mail Tools

Compose Tools

Duplicate Remover Tools

Mail Tools for Outlook

Online Services

Calendar Tools

Schedule Management

Calendar Printing Tools

Calendar Reminder Tools

Calendar Dates & Data

Time and Billing Tools

Meeting Productivity Tools

Duplicate Remover Tools

Productivity

Productivity Tools

Automatic Message Processing Tools

Special Function Automatic Processing Tools

Housekeeping and Message Management

Task Tools

Project and Business Management Tools

Choosing the Folder to Save a Sent Message In

Run Rules on messages after reading

Help & Suggestions

Submit Outlook Feature Requests

Slipstick Support Services

Buy Microsoft 365 Office Software and Services

Visit Slipstick Forums.

What's New at Slipstick.com

Home | Outlook User | Exchange Administrator | Office 365 | Outlook.com | Outlook Developer
Outlook for Mac | Common Problems | Utilities & Addins | Tutorials
Outlook & iCloud Issues | Outlook Apps
EMO Archives | About Slipstick | Slipstick Forums
Submit New or Updated Outlook and Exchange Server Utilities

Send comments using our Feedback page
Copyright © 2026 Slipstick Systems. All rights reserved.
Slipstick Systems is not affiliated with Microsoft Corporation.

:wpds_smile::wpds_grin::wpds_wink::wpds_mrgreen::wpds_neutral::wpds_twisted::wpds_arrow::wpds_shock::wpds_unamused::wpds_cool::wpds_evil::wpds_oops::wpds_razz::wpds_roll::wpds_cry::wpds_eek::wpds_lol::wpds_mad::wpds_sad::wpds_exclamation::wpds_question::wpds_idea::wpds_hmm::wpds_beg::wpds_whew::wpds_chuckle::wpds_silly::wpds_envy::wpds_shutmouth:
wpDiscuz

Sign up for Exchange Messaging Outlook

Our weekly Outlook & Exchange newsletter (bi-weekly during the summer)






Please note: If you subscribed to Exchange Messaging Outlook before August 2019, please re-subscribe.

Never see this message again.

You are going to send email to

Move Comment