The following code saves the attachments from selected messages but does not delete the attachments from the message(s). This VBA code is based on the code sample from my Outlook book: Save and Delete Attachments. Use it if you want to save the attachment, add a link to the saved file, and delete the attachment from the message.
Instructions to add the macro to a toolbar button or ribbon command are at the end of the page.
Save Attachments to the hard drive
Copy and paste the code from this page into your ThisOutlookSession project.
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.
To use it you must first create a folder under your My Documents named OLAttachments (the code will not create it for you). Then select one or more messages and run the macro to save the attachments. You'll need to set macro security to warn before enabling macros or sign the macro. You can change the folder name or path where the attachments are saved by editing 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 = Application ' Get the collection of selected objects. Set objSelection = objOL.ActiveExplorer.Selection ' The attachment folder needs to exist ' You can change this to another folder name of your choice ' Set the Attachment folder. strFolderpath = strFolderpath & "\OLAttachments\" ' Check each selected item for attachments. For Each objMsg In objSelection Set objAttachments = objMsg.Attachments lngCount = objAttachments.Count If lngCount > 0 Then ' 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 ' 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 Next i End If Next ExitSub: Set objAttachments = Nothing Set objMsg = Nothing Set objSelection = Nothing Set objOL = Nothing End Sub
Use an ItemAdd to Save Attachments on Arrival
This macro runs (automatically) on messages as they are added to the Inbox. Put it in ThisOutlookSession.
Option Explicit Private WithEvents olInboxItems As Items Private Sub Application_Startup() Dim objNS As NameSpace Set objNS = Application.Session ' instantiate objects declared WithEvents Set olInboxItems = objNS.GetDefaultFolder(olFolderInbox).Items Set objNS = Nothing End Sub Private Sub olInboxItems_ItemAdd(ByVal Item As Object) On Error Resume Next If Item.Attachments.Count > 0 Then Dim objAttachments As Outlook.Attachments Dim lngCount As Long Dim strFile As String Dim sFileType As String Dim i as long Set objAttachments = Item.Attachments lngCount = objAttachments.Count For i = lngCount To 1 Step -1 ' Get the file name. strFile = objAttachments.Item(i).FileName ' Get the path to your My Documents folder strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16) strFolderpath = strFolderpath & "\OLAttachments\" ' Combine with the path to the folder. strFile = strFolderpath & strFile ' Save the attachment as a file. objAttachments.Item(i).SaveAsFile strFile Next i End If End Sub
Use Predefined Folders
This set of macros allows you to define a set of folders to save attachments to. Set the folder path in the small "stub" macros. The folder name is passed to the main macro. Add the macros to the ribbon or Quick Access Toolbar so they are easy to use.
To use: Select one or more messages that have attachments and run the macro.
To create more locations, copy a stub macro, then change the path and macro name. You need to end the file path with a \.
As written, the macro saves all attachments on the selected messages. If you need to filter it by file type, see the examples in other macros on this page.
These macros go in a Module.
Public strFolderpath As String Public Sub SaveToDiane() strFolderpath = "c:\diane\" SaveAttachments End Sub Public Sub SaveToProject() strFolderpath = "C:\project1\" SaveAttachments End Sub Private Sub SaveAttachments() Dim objOL As Outlook.Application Dim objMsg As Object Dim objAttachments As Outlook.Attachments Dim objSelection As Outlook.Selection Dim i As Long Dim lngCount As Long Dim strFile As String On Error Resume Next Set objOL = Application Set objSelection = objOL.ActiveExplorer.Selection ' Check each selected item for attachments. For Each objMsg In objSelection Set objAttachments = objMsg.Attachments lngCount = objAttachments.Count If lngCount > 0 Then ' 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 ' Get the file name. strFile = objAttachments.Item(i).FileName ' Combine with the path to the folder. strFile = strFolderpath & strFile ' Save the attachment as a file. objAttachments.Item(i).SaveAsFile strFile Next i End If Next ExitSub: Set objAttachments = Nothing Set objMsg = Nothing Set objSelection = Nothing Set objOL = Nothing End Sub
Run a Script Rule to Save Attachments
This version of the macro works with Rules, saving all attachments in messages that meet the condition of the rule to a folder under the user's documents folder.
To learn more about run a script rules, see Outlook's Rules and Alerts: Run a Script.
Public Sub SaveAttachments(Item As Outlook.MailItem) If Item.Attachments.Count > 0 Then Dim objAttachments As Outlook.Attachments Dim lngCount As Long Dim strFile As String Dim sFileType As String Dim i As Long Set objAttachments = Item.Attachments lngCount = objAttachments.Count For i = lngCount To 1 Step -1 ' Get the file name. strFile = objAttachments.Item(i).FileName ' Get the path to your My Documents folder strfolderpath = CreateObject("WScript.Shell").SpecialFolders(16) strfolderpath = strfolderpath & "\Attachments\" ' Combine with the path to the folder. strFile = strfolderpath & strFile ' Save the attachment as a file. objAttachments.Item(i).SaveAsFile strFile Next i End If End Sub
Add the message date to the filename
If you want to add the message date to the file, you'll need to get the date from the SentOn or ReceivedDate fields then format it as a string before adding it to the file name. It's a total of 4 new lines and one edited line.
First, Dim the two new variables at the top of the macro:
Dim dtDate As Date Dim sName As String
To format the date and time and add it to the filename in 20130905045911-filename format, you'll add two lines of code after you count the attachments to get the date and format it, then edit the line that creates the filename.
If lngCount > 0 Then dtDate = objMsg.SentOn sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, vbUseSystem) & Format(dtDate, "hhnnss", vbUseSystemDayOfWeek, vbUseSystem) & "-" For i = lngCount To 1 Step -1 ' Get the file name. strFile = sName & objAttachments.Item(i).FileName
Use the Subject and remove illegal characters
If you use the email subject in the file name, you will need to remove illegal characters that are not supported in Windows file system.
You can do that using the ReplaceCharsForFileName function (below). As written, the illegal characters are replaced with a dash (-) but you can change the word seperator.
Use this to get the subject and remove the illegal characters.
If lngCount > 0 Then sSubject = objMsg.Subject ' change the seperator if desired sSubject = ReplaceCharsForFileName sSubject, "-" For i = lngCount To 1 Step -1 ' Get the file name. strFile = sSubject & objAttachments.Item(i).FileName
To trim long subjects, use the Left function to get the first characters. This snippet uses the first 25 characters of the subject.
sSubject = left(objMsg.Subject, 25)
To use the date and subject, use this code:
If lngCount > 0 Then sSubject = objMsg.Subject sSubject = ReplaceCharsForFileName sSubject, "-" dtDate = objMsg.SentOn sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, vbUseSystem) & Format(dtDate, "hhnnss", vbUseSystemDayOfWeek, vbUseSystem) & "-" For i = lngCount To 1 Step -1 strFile = sSubject & sName & objAttachments.Item(i).FileName
Public Sub ReplaceCharsForFileName(sSubject As String, _ sChr As String _ ) sSubject = Replace(sSubject, "'", sChr) sSubject = Replace(sSubject, "*", sChr) sSubject = Replace(sSubject, "/", sChr) sSubject = Replace(sSubject, "\", sChr) sSubject = Replace(sSubject, ":", sChr) sSubject = Replace(sSubject, "?", sChr) sSubject = Replace(sSubject, Chr(34), sChr) sSubject = Replace(sSubject, "<", sChr) sSubject = Replace(sSubject, ">", sChr) sSubject = Replace(sSubject, "|", sChr) End Sub
Don't save images in signatures
This macro saves all attachments, including images embedded in signatures (they are attachments after all). To avoid saving signature images, you have two options: don't save image files, or don't save smaller files. You could even do both and save only larger images files.
Replace the code between For i = lngCount To 1 Step -1 / Next i lines with the following to filter out files smaller than 5KB. This should catch most signature images (and many text files).
If the attachments you need to save are always over 5 KB, you can increase the file size. (For reference, a blank Word document is over 10KB.)
For i = lngCount To 1 Step -1 If objAttachments.Item(i).Size > 5200 Then ' 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 End If Next i
Save by File type
If you want to skip or save only a specific file type, use If LCase(Right(strFile, 4)) <> ".ext" format, where .ext is the extension. Add it after the first line strFile = line (and don't forget to add the End if before the Next i). You can use it to exclude a file type or use an equal (=) sign to save only a specific file type. (For 4-character extensions, use only the characters, don't include the dot.)
To work with a longer list of file types, use a Select Case statement. In this example, we're looking for image attachments, and if less than approx 5KB, we skip them. Larger image attachments will be saved.
For i = lngCount To 1 Step -1 ' Get the file name. strFile = objAttachments.Item(i).filename ' This code looks at the last 4 characters in a filename sFileType = LCase$(Right$(strFile, 4)) Select Case sFileType ' Add additional file types below Case ".jpg", ".png", ".gif" If objAttachments.Item(i).Size < 5200 Then GoTo nexti End If End Select ' Combine with the path to the Temp folder. strFile = strFolderpath & strFile ' Save the attachment as a file. objAttachments.Item(i).SaveAsFile strFile nexti: Next i
Increment duplicate file names
This version of the macro check to see if the file exists, it so, it adds a number to the file name.
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 = Application ' Get the collection of selected objects. Set objSelection = objOL.ActiveExplorer.Selection ' The attachment folder needs to exist ' You can change this to another folder name of your choice ' Set the Attachment folder. strFolderpath = strFolderpath & "\" ' Check each selected item for attachments. For Each objMsg In objSelection Set objAttachments = objMsg.Attachments lngCount = objAttachments.Count If lngCount > 0 Then ' 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 ' Get the file name. strFile = objAttachments.Item(i).Filename lCount = InStrRev(strFile, ".") - 1 pre = Left(strFile, lCount) ext = Right(strFile, Len(strFile) - lCount) ' Combine with the path to make the final path strFile = strFolderpath & pre & ext 'check for existing Dim nnumber As String nnumber = 0 Do FileExists = Dir(strFile) If FileExists = "" Then Exit Do Else nnumber = nnumber + 1 strFile = strFolderpath & pre & "(" & nnumber & ")" & ext End If Loop Debug.Print strFile objAttachments.Item(i).SaveAsFile strFile Next i End If Next ExitSub: Set objAttachments = Nothing Set objMsg = Nothing Set objSelection = Nothing Set objOL = Nothing End Sub
Add a number to each attachment
This macro merges the first macro on this page with the macro at Write the last used value to the registry sample to add a number to each saved attachment, incrementing as attachments are saved. Because the last used value is in the registry, the count will persist because restarts.
Get the complete macro, ready to use: AttachmentIndex
' HKEY_CURRENT_USER\Software\VB and VBA Program Settings\Outlook\Index sAppName = "Outlook" sSection = "Index" sKey = "Last Index Number" ' The default starting number. iDefault = 101 ' adjust as needed ' Get stored registry value, if any. lRegValue = GetSetting(sAppName, sSection, sKey, iDefault) ' If the result is 0, set to default value. If lRegValue = 0 Then lRegValue = iDefault ' Put the save attachment code here strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16) On Error Resume Next Set objOL = Application Set objSelection = objOL.ActiveExplorer.Selection strFolderpath = strFolderpath & "\OLAttachments\" For Each objMsg In objSelection Set objAttachments = objMsg.Attachments lngCount = objAttachments.Count If lngCount > 0 Then For i = lngCount To 1 Step -1 ' Get the file name. strFile = objAttachments.Item(i).fileName lcount = InStrRev(strFile, ".") - 1 pre = Left(strFile, lcount) ext = Right(strFile, Len(strFile) - lcount) ' Combine with the path to make the final path strFile = strFolderpath & pre & "_" & lRegValue & ext strFile = strFolderpath & strFile objAttachments.Item(i).SaveAsFile strFile ' add 1 to the index lRegValue = lRegValue + 1 Err.Clear Next ' update the registry at the end SaveSetting sAppName, sSection, sKey, lRegValue
Save Attachments in Subfolders
To save the attachments in subfolders, you need to use the File Scripting Object to create the folder if it does not exist.
A complete, ready-to-use sample macro is here.
For Each objMsg In objSelection ' Set the Attachment folder. strFolder = strFolderpath & "\OLAttachments\" Set objAttachments = objMsg.Attachments ' put it together with the sender name strFolder = strFolder & objMsg.SenderName & "\" ' if the sender's folder doesn't exist, create it If Not FSO.FolderExists(strFolder) Then FSO.CreateFolder (strFolder) End If lngCount = objAttachments.Count If lngCount > 0 Then For i = lngCount To 1 Step -1 strFile = objAttachments.Item(i).FileName strFile = strFolder & strFile objAttachments.Item(i).SaveAsFile strFile
Use Macro with Different Folders
This version of the macro save the attachments on the selected message to a subfolder. By using a "stub macro" to set the name of the subfolder, you can don't need ot repeat the long macro multiple times to use it with different pre-defined folders.
In this example, I'm either saving the attachment to From Bob or From Jim folder in my Documents folder.
C:\Users\username\Documents\From Bob\
C:\Users\username\Documents\From Jim\
Create buttons on the ribbon for the stub macros. Select the message then click the appropriate button.
Dim strFolder As String Public Sub SaveToFolderBob() strFolder = "From Bob" SaveAttachments End Sub Public Sub SaveToFolderJim() strFolder = "From Jim" SaveAttachments End Sub Private 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) Debug.Print strFolderpath On Error Resume Next ' The attachment folder needs to exist ' You can change this to another folder name of your choice ' Set the Attachment folder. strFolderpath = strFolderpath & "\" & strFolder & "\" Debug.Print strFolderpath Set objOL = Outlook.Application Set objMsg = objOL.ActiveExplorer.Selection.Item(1) Set objAttachments = objMsg.Attachments lngCount = objAttachments.Count If lngCount > 0 Then ' 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 ' 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 Next i End If ExitSub: Set objAttachments = Nothing Set objMsg = Nothing Set objSelection = Nothing Set objOL = Nothing End Sub
Assign the macro to a button
In Outlook 2007 and older, you can create a toolbar button to run the macro. In Outlook 2010, you'll need to customize the ribbon.
More information is at Customize the Outlook Toolbar, Ribbon or QAT and at Customizing the Quick Access Toolbar (QAT).
Run the macro using a ribbon or QAT shortcut
Step 1: To create a button to run a macro in Outlook 2010, go to File, Options, and choose Customize Ribbon. (If you want a button on the QAT, choose Quick Access Toolbar instead.)
Step 2: Choose Macro from the Choose Commands From menu and select the macro you want to add to the ribbon or QAT.
Step 3: Select the Group you want to add the macro to. If it doesn't exist yet, use the New Group buttons to create the group.
Step 4: Use the Rename button to give the macro a friendly name and change the icon. You are limited to the icons in the dialog (unless you want to program a ribbon command).
Run the macro from a toolbar button
To create a toolbar button for it, go to View, Toolbar, Customize, Commands tab. In the Categories pane, type M to jump to Macros. On the Commands side, drag the macro you created to the toolbar. Right click on the button to rename it and assign a new icon.
WOW! Thanks Diane. Greetings from New Zealand. You saved me from having to click on 50 different email attachments. My fingers thank you.
Hi Diane
to is this correct?Does "Increment duplicate file names" work with Outlook 365?
I wanted my own file path so I changed
Thanks!
Edit: I noticed when I read my post that I've missed the last "\" in my path.
The desktop Outlook that is installed with Microsoft 365 Office subscription software, yes it works with it. Outlook on the web, no.
Jesus God in Heaven, Thank you Diane Poremsky
You've coded your way into my heart.
A blessing on your head. Mazeltov.
Forever grateful,
Amen.
Thanks Diane! This has been extremely helpful. I am looking at saving excel files to a local drive; however, the excel files have their first 3 rows completely blank. Is there anyway to delete those rows upon download?
Thanks in advance!
You would need to use an Excel macro to do that. It could be converted to an Outlook macro that opens the file and deletes the empty rows. I don't have a macro that does it though.
Hi Diane! Thank you for your codes, they'll be saving me a lot of time. I'm using the "Use the Subject and remove illegal characters" one but the files are getting renamed to the subject + the original filename. Is there any way to make it so that it renames the files to the subject only? I'm new to VBA and I didn't manage to modify it myself.
Thanks Diane!
This is an incredible source. I attempted to combine two of your codes (Save Attachments in Subfolders and Increment duplicate file names), but did not succeed. Is it possible to do this?
It is possible. I'll take a look.
It is possible. I did not test, but this should work. { fingers crossed } Public Sub SaveinSenderFolder() 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, strFolder As String Dim strDeletedFiles As String Dim FSO As Object Set FSO = CreateObject("Scripting.FileSystemObject") strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16) ' On Error Resume Next Set objOL = Application Set objSelection = objOL.ActiveExplorer.Selection ' The attachment folder needs to exist ' You can change this to another folder name of your choice ' Check each selected item for attachments. For Each objMsg In objSelection ' Set the Attachment folder. strFolder = strFolderpath & "\OLAttachments\" Set objAttachments = objMsg.Attachments strFolder = strFolder & objMsg.SenderName & "\" ' if the sender's folder doesn't exist, create it If Not FSO.FolderExists(strFolder) Then FSO.CreateFolder (strFolder) End If lngCount = objAttachments.Count If lngCount > 0 Then ' 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 ' Get the file name. strFile… Read more »
hey diana, I'd your expertise on this: why is it keeping telling me that a label is missing, using the following code? Public Sub SaveToProject() strFolderpath = "C:\Users\Desktop\Test\" SaveAttachments End Sub Private Sub SaveAttachments() Dim objOL As Outlook.Application Dim objMsg As Object Dim objAttachments As Outlook.Attachments Dim objSelection As Outlook.Selection Dim i As Long Dim sFileType As String Dim lngCount As Long Dim strFile As String On Error Resume Next Set objOL = Application Set objSelection = objOL.ActiveExplorer.Selection ' Check each selected item for attachments. For Each objMsg In objSelection Set objAttachments = objMsg.Attachments lngCount = objAttachments.Count If lngCount > 0 Then ' 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 ' Get the file name. strFile = objAttachments.Item(i).FileName ' This code looks at the last 4 characters in a filename sFileType = LCase$(Right$(strFile, 4)) Select Case sFileType ' Add additional file types below Case ".pdf" If objAttachments.Item(i).Size < 5200 Then GoTo nexti End If End Select ' Combine with the path to the folder. strFile =… Read more »