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
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
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.
Hi. What if I need to save .xls files to .txt format automatically form Outlook to certain folder?
So, basically, you need to open them in Excel, save as text? You can do it using the excel object model - easiest way to get the code is to record a macro in excel then tweak it to work from outlook. Which is basically, change the activeworkbook reference to an excel object.
ActiveWorkbook.SaveAs Filename:= _
"path & filename.txt", _
FileFormat:=xlText, CreateBackup:=False
End Sub
I have several macros that show how to work with outlook and excel, such as https://www.slipstick.com/developer/vba-copy-outlook-email-excel-workbook/
Great stuff, Diane. I know Excel VBA pretty well but needed to save a bunch of CSVs from a number of emails and didn't know where to start with Outlook VBA. This worked out great.
A couple of observations:
I had to turn off Outlooks' reading pane. With the reading pane on, objOL.ActiveExplorer.Selection is only the displayed email, no matter how many you actually have selected.
My CSVs saved with a funky encoding. According to Notepad++ it's "UCS-2 LE BOM". It also saved the CSVs with an @ between each character, like "o@r@d@e@r@". I got rid of those in a linux shell with cat filename | tr -d '@' > newfilename.
Hmm. I have never seen that. Is notepad set to a format other than UTF-8?
Hi Diane, thanks for creating this wonderful piece of code.
But how to append sender's email id before the attachment name and then save all the attachments?
Using the date snippet in the article, replace the date code with the sender's email.
Get the address:
sName = objMsg.senderemailaddress
You'd use this for the file name (as it is in the date snippet code)
strFile = sName & objAttachments.Item(i).FileName
Hi Diane,
How to save attachments from arrived mails of closed Outlook.means when the system is not ON or outlook is not yet opened.
Windows definitely needs to be running to use any client-side method. Outlook needs to be running to use a macro. A vbs or powershell could open outlook, but if the mail was not downloaded previously, you'd need to wait for outlook to download it. Powershell can connect to an exchange mailbox, but it would probably be easier to use Flow (or another 'this-then-that' service to save attachments to cloud storage. since Flow (and others) are web services, they'd work even if your workstation is off.
Hello Diane,
I am trying touse the code that runs automatically from above but I'm getting no success.
I had tryed to set the file path to a custom destination but upted to just do the OLAttachments folder inside documents and still nada
Any advise?
Here's my code
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
Dim strFolderpath As String
Set objAttachments = Item.Attachments
lngCount = objAttachments.Count
For i = lngCount To 1 Step -1
' Get the file name.
strFile = objAttachments.Item(i).FileName
On Error GoTo 1
' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
strFolderpath = strFolderpath & "C:\Documents\OLAttachments\"
' Combine with the path to the folder.
1 strFile = strFolderpath & strFile
' Save the attachment as a file.
objAttachments.Item(i).SaveAsFile strFile
Next i
End If
End Sub
this is one problem: strFolderpath = strFolderpath & "C:\Documents\OLAttachments\"
use just strFolderpath = "C:\Documents\OLAttachments\" or the correct path to the folder (documents is under C:\users\username by default)
Create the attachments folder in Documents, open it and copy the path from the address bar. path it in for the path.
Hello Daine, amazing codes, thanks for sharing.
Have to requests
1) how to remove special characters from subject line. I have added objMsg.Subject to capture the subject in the code for Save Attachments in Subfolders2) unable to save the mail attached as an attachment, its giving error.
Much thanks
You need to use a function to strip illegal characters -
in the macro use
sName = objmsg.Subject
ReplaceCharsForFileName sName, "-"
then use sName in the link that sets the file name
I added a code sample to the article to remove the illegal characters.
https://www.slipstick.com/developer/save-attachments-to-the-hard-drive/#illegal
I am using below coded save the file to purticular folder. I tried using this code however its not getting attachement saved to designated folder. I am using Outlook 2016, Windows 10. Once I run macro there no error. Kindly advise.
Sub Download_Attachments()
Dim ns As NameSpace
Dim olFolder_Inbox As Folder
Dim olMail As MailItem
Dim olAttachment As Attachment
Dim fso As Object
Dim Files_Saved_Folder_Path As String
Files_Saved_Folder_Path = "<Your folder path>"
Set ns = GetNamespace("MAPI")
Set fso = CreateObject("Scripting.FileSystemObject")
Set olFolder_Inbox = ns.GetDefaultFolder(olFolderInbox)
For Each olMail In olFolder_Inbox.Items
If TypeName(olMail) = "MailItem" And olMail.Attachments.Count > 0 Then
fso.CreateFolder (fso.BuildPath(File_Saved, Trim(olMail.Subject)))
For Each olAttachment In olMail.Attachments
olAttachment.SaveAsFile fso.BuildPath(File_Saved, Trim(olMail.Subject)) & "\" & olAttachment.FileName
Next olAttachment
End If
Next olMail
Set olFolder_Inbox = Nothing
Set fso = Nothing
Set ns = Nothing
End Sub
What are you using for the file path?
Files_Saved_Folder_Path = "<Your folder path>" ?
It needs to be c:\the\path\ <== ending \. If you don't have a slash between the file path and name, the file will be saved as 'pathfilename'
Are you setting the File_Saved variable?
fso.CreateFolder (fso.BuildPath(File_Saved, Trim(olMail.Subject)))
Is there a Macro to copy attachments from recurring meetings to the hard drive
By using Dim objMsg As Object, the first macro should work with any outlook item. Are there different attachments on each occurrence? That is a little trickier. I'm not sure if i have any code for that.
Thank you very much for quick response, Yes, different attachments in each occurrence.