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

Save Messages and Attachments to a New Folder

Slipstick Systems

› Developer › Code Samples › Save Messages and Attachments to a New Folder

Last reviewed on October 4, 2016     41 Comments

Joel asked

I get a lot of pictures from a photographer, he writes the details in the email body. Is there a way to save each email in a separate folder, the name should be the subject line? and the email body should be saved as a text file?

Sure, you can do this using VBA.

This macro creates a folder in your Documents folder using the subject name (after removing any illegal characters) and then saves the message (as HTML) and any attachments to the folder.
Save email messages to the hard drive

If you want the message saves as a text or doc file, change
objMsg.SaveAs strFolderpath & strName & ".htm", olHTML to
objMsg.SaveAs strFolderpath & strName & ".txt", olTXT or
objMsg.SaveAs strFolderpath & strName & ".rtf", olRTF

To save it as a message file, use
objMsg.SaveAs strFolderpath & strName & ".msg", olMsg

To use, select the message then run the macro.


Public Sub SaveMessagesAndAttachments()
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 strName As String
Dim strFolderpath As String
Dim strDeletedFiles As String
 Dim sFileType As String
Dim enviro As String
enviro = CStr(Environ("USERPROFILE"))
    
Dim fso As Object
Dim oldName
    
Set fso = CreateObject("Scripting.FileSystemObject")
      
    On Error Resume Next
Set objOL = CreateObject("Outlook.Application")
Set objMsg = objOL.ActiveExplorer.Selection.Item(1)
 strName = StripIllegalChar(objMsg.Subject)
    
strFolderpath = enviro & "\Documents\" & strName & "\"
If Not fso.FolderExists(strFolderpath) Then
    fso.CreateFolder (strFolderpath)
End If

 objMsg.SaveAs strFolderpath & strName & ".htm", olHTML
 
    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count
         
    If lngCount > 0 Then
     
    For i = lngCount To 1 Step -1
     
    strFile = objAttachments.Item(i).FileName
    Debug.Print strFile
    strFile = strFolderpath & strFile
    objAttachments.Item(i).SaveAsFile strFile
   
    Next i
    End If
          
ExitSub:
 
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

Function StripIllegalChar(StrInput)
    Dim RegX            As Object    
    Set RegX = CreateObject("vbscript.regexp")
       
    RegX.Pattern = "[\" & Chr(34) & "\!\@\#\$\%\^\&\*\(\)\=\+\|\[\]\{\}\`\'\;\:\<\>\?\/\,]"
    RegX.IgnoreCase = True
    RegX.Global = True
       
    StripIllegalChar = RegX.Replace(StrInput, "")
       
ExitFunction:
    Set RegX = Nothing
       
End Function

 

Save Attachment to a Specific Folder

This version of the macro saves the attached images to a specific folder using a filename format that includes the date. I use this to save images from incoming email. If you want to save the files but don't want to rename them, remove the lines that change the oldName to the newname.

Select the message then run the macro.

Public Sub SaveAttachments()
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
 Dim sFileType As String
Dim enviro As String
enviro = CStr(Environ("USERPROFILE"))
    
Dim fso As Object
Dim oldName
    
Set fso = CreateObject("Scripting.FileSystemObject")
      
    On Error Resume Next
Set objOL = CreateObject("Outlook.Application")
Set objMsg = objOL.ActiveExplorer.Selection.Item(1)
    
strFolderpath = enviro & "\Attachments\" '& Format(objMsg.SentOn, "yymd")
 
    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
   
'Get the file name
 Set oldName = fso.GetFile(strFile)
 Debug.Print oldName
 sFileType = LCase$(Right$(oldName, 6))
 Debug.Print sFileType

 DateFormat = Format(objMsg.SentOn, "yymmdd-")
 newName = "RC" & DateFormat & sFileType
 Debug.Print newName
 oldName.Name = newName
 
    Next i
    End If
          
ExitSub:
 
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub 

Save a Message and Attachments to a New Folder

This is the macro I use to save a message and it's attachments to a new folder named for the message subject. I shorten the subject to 40 characters to avoid problems with long file names.

To use, select one message and run the macro. If more than one message is selected, it runs only on the first message.

Public Sub SaveMessagesAndAttachments()
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 StrName As String
Dim strTime 'As String
Dim StrFolderPath As String
    
Dim FSO As Object
Dim oldName
    
Set FSO = CreateObject("Scripting.FileSystemObject")
      
On Error Resume Next
Set objOL = Outlook.Application
Set objMsg = objOL.ActiveExplorer.Selection.Item(1)

' remove illegal characters and shorten name
 StrName = StripIllegalChar(objMsg.Subject)
 StrName = Left(StrName, 40)
       
strTime = DateValue(objMsg.ReceivedTime) '& TimeValue(objMsg.ReceivedTime)

' I use this to reduce changes of duplicate names
strTime = Format(objMsg.ReceivedTime, "-hhmmss")
Debug.Print strTime
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
    Debug.Print strFolderpath
    On Error Resume Next
StrFolderPath = StrFolderPath & "\Attachments\" & StrName & strTime & "\"

' create folder if doesn't exist
If Not FSO.FolderExists(StrFolderPath) Then
    FSO.CreateFolder (StrFolderPath)
End If

' Save message and as html and doc file type
 objMsg.SaveAs StrFolderPath & StrName & ".msg", olMsg
 objMsg.SaveAs StrFolderPath & StrName & ".doc", olRTF
 objMsg.SaveAs StrFolderPath & StrName & ".htm", olHTML
 
 'save any attachments also
    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count
         
    If lngCount > 0 Then
     
    For i = lngCount To 1 Step -1
     
    StrFile = objAttachments.Item(i).FileName
    Debug.Print StrFile
    StrFile = StrFolderPath & StrFile
    objAttachments.Item(i).SaveAsFile StrFile
   
    Next i
    End If
          
ExitSub:
 
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

How to use macros

First: You will need macro security set to low during testing.

To check your macro security in Outlook 2010 or 2013, go to File, Options, Trust Center and open Trust Center Settings, and change the Macro Settings. In Outlook 2007 and older, it’s at Tools, Macro Security.

After you test the macro and see that it works, you can either leave macro security set to low or sign the macro.

Open the VBA Editor by pressing Alt+F11 on your keyboard.

To put the code in a module:

  1. Right click on Project1 and choose Insert > Module
  2. Copy and paste the macro into the new module.

More information as well as screenshots are at How to use the VBA Editor

Save Messages and Attachments to a New Folder was last modified: October 4th, 2016 by Diane Poremsky

Related Posts:

  • Save and Delete Attachments from Outlook messages
  • 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
41 Comments
newest
oldest most voted
Inline Feedbacks
View all comments

César
October 27, 2023 1:00 am

Hi Diane, thanks so much for your great solutions. I'd like to get a kind of mix of the 2 codes of you shown below.

My question is.

How to save selected emails as docx or pdf, each with its respective attachments (if any) in a folder named = email subject?

https://www.slipstick.com/developer/code-samples/save-messages-and-attachments-in-a-new-folder/

https://www.slipstick.com/developer/convert-messages-rtf-format-save-doc-file-type/

Last edited 1 year ago by César
0
0
Reply
Frank
June 16, 2018 1:31 pm

Im trying to save as a pdf instead of an html. Changing hmtl to PDF doesn't work.

objMsg.SaveAs strFolderpath &amp; strName &amp; " - " &amp; SName &amp; ".htm", olHTML

0
0
Reply
Diane Poremsky
Author
Reply to  Frank
June 18, 2018 7:29 am

That won't work if the message is not pdf. This shows hwo to do it https://www.slipstick.com/developer/code-samples/save-outlook-email-pdf/ - it saves selected messages as pdf, so you could call it from the macro on this page - although it won't save in the same folder as the others without tweaking.

0
0
Reply
Sam
June 10, 2018 3:14 pm

I've tried everything I can, but I can't get this to work with a do loop.

How can I use the first code above, but so It will work with all emails that I have selected?

0
0
Reply
Diane Poremsky
Author
Reply to  Sam
June 11, 2018 12:54 am

Replace:
On Error Resume Next
Set objOL = CreateObject("Outlook.Application")
Set objMsg = objOL.ActiveExplorer.Selection.Item(1)

With these lines:
Dim objItems As Outlook.Items
Dim objFolder As Outlook.MAPIFolder

Set objOL = Outlook.Application
Set objFolder = objOL.ActiveExplorer.CurrentFolder
Set objItems = objFolder.Items
For Each objMsg In objItems

After the end if, add this:
Next

0
0
Reply
Sam
Reply to  Diane Poremsky
June 12, 2018 2:04 pm

I'm still having issues. When I add your modifications, I'm able to make it output the folder names, but nothing goes into the folders. Here is my original code that works when I select (1) email. If I replace what you're saying it doesn't work. Public Sub SaveEmailsAndAttachments() 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 dtDate As Date Dim SName As String Dim strName As String Dim strFolderpath As String Dim strDeletedFiles As String Dim sFileType As String Dim fso As Object Dim oldName Set fso = CreateObject("Scripting.FileSystemObject") On Error Resume Next Set objOL = CreateObject("Outlook.Application") Set objMsg = objOL.ActiveExplorer.Selection.Item(1) strName = StripIllegalChar(objMsg.Subject) strFolderpath = "E:\Downloads\" &amp; strName &amp; "\" If Not fso.FolderExists(strFolderpath) Then fso.CreateFolder (strFolderpath) End If Set objAttachments = objMsg.Attachments lngCount = objAttachments.Count If lngCount &gt; 0 Then dtDate = objMsg.SentOn SName = Format(dtDate, "yyyy-mm-dd", vbUseSystemDayOfWeek, vbUseSystem) For i = lngCount To 1 Step -1 If objAttachments.Item(i).Size &gt; 5200 Then strFile = objAttachments.Item(i).FileName Debug.Print strFile strFile = strFolderpath &amp; SName &amp; " - " &amp; strFile objAttachments.Item(i).SaveAsFile strFile objMsg.SaveAs strFolderpath &amp; strName &amp; " - " &amp; SName &amp;… Read more »

0
0
Reply
Diane Poremsky
Author
Reply to  Sam
June 14, 2018 12:36 am

Except for wordpress screwing up the ampersands and greater thans, the code looks ok and more importantly, it works when i tested it here.

0
0
Reply
Kurt
April 27, 2017 12:29 pm

Diane, I took your savemessagesand attachments and tried to incorporate your browse function. But am having a few issues. Can you look at my script and advise. ? Thanks, KURT issues: 1) Folder not being created. (with quoteID number from subject lline) 2) E-mail msg is being saved, attachements are saved. to path below. I would like them saved to a folder that I have created and named from number in the subject line. 3) attachments are being named which ever folder I pick from browse.( I just want attachments to be saved what ever they are named in e-maiil) Public Sub SaveMessagesAndAttachments() 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 StrName As String Dim StrFolderPath As String Dim strPath As String Dim sFileType As String Dim FSO As Object Dim oldName Set FSO = CreateObject("Scripting.FileSystemObject") On Error Resume Next Set objOL = CreateObject("Outlook.Application") Set objMsg = objOL.ActiveExplorer.Selection.Item(1) StrName = Left(StrName, 6) ' quoteID number is 6 characters. StrFolderPath = BrowseForFolder("P:Clients17") ' create folder if doesn't exist If Not FSO.FolderExists(StrFolderPath) Then FSO.CreateFolder (StrFolderPath) End If ' Save message as msg file type… Read more »

0
0
Reply
Diane Poremsky
Author
Reply to  Kurt
May 25, 2017 8:27 am

Sorry I missed this earlier. The problem with the code is a missing slash at the end of the folder path so it thinks the selected folder is part of the file name. Add the slash to the strfolderpath right after you select the folder. (If wordpress/php removes the slash, it belongs inside the quotes at the end.)

StrFolderPath = BrowseForFolder("P:\Clients17")
StrFolderPath = StrFolderPath & "\"

(looks like wordpress left the slash but screwed up the 'and' sign. :( )

0
0
Reply
Diane Poremsky
Author
Reply to  Diane Poremsky
May 25, 2017 8:32 am

The macro I tested (and works here) is attached.

Save messages attachments.txt
0
0
Reply
Diane Poremsky
Author
Reply to  Kurt
May 25, 2017 8:38 am

Sheesh - I missed #1 - use this for the strfolderpath:

StrFolderPath = BrowseForFolder("P:\Clients17")
StrFolderPath = StrFolderPath & "\" & StrName & "\"

0
0
Reply
Kurt
April 11, 2017 1:51 pm

Hello, I am trying the save message and attachments, when I run. I get compile error: sub or function not defined. on thisline.

StrName = StripIllegalChar(objMsg.Subject)

Am I doing something wrong ?

0
0
Reply
Diane Poremsky
Author
Reply to  Kurt
April 11, 2017 3:08 pm

Do you have the StripIllegalChar function? It's at the need of the first macro on the page.

0
0
Reply
Kurt
Reply to  Diane Poremsky
April 12, 2017 12:45 pm

OK. I added the StripIllegalChar function, it works now.

I would like to modify this. Instead of saving folder to a specific destination, I would like to have window open to choose location to save folder.
Can you help with that ?

Kurt

0
0
Reply
Diane Poremsky
Author
Reply to  Kurt
April 14, 2017 12:37 am

You need to use the browseforfolder function - https://www.slipstick.com/developer/code-samples/windows-filepaths-macro/

0
0
Reply
Tuan
January 8, 2017 12:09 pm

Hi,
I am new to this forum and novice to VBA.
When I run the third code above, there is an error
"Outlook can not save or create this file. Make sure that the disk you want to save the file on is not full, write protected or damaged"
It work with the 2 other codes, so I don't think it is error about the right to save files.

What could be the reasons and how to fix.
Thks

0
0
Reply
Petar
August 2, 2016 5:38 am

Hi,
what code will be, if i wanted to save selected messages and attachments separately (one mail per folder). Name of folder should be subject + date + time or sender mail adress + date + time. In folder should be saved mail in txt/html format and all attachments from that mail.

0
0
Reply
Diane Poremsky
Author
Reply to  Petar
October 4, 2016 12:34 pm

This part of the code sets it to be saved in a folder that uses the message subject:
strName = StripIllegalChar(objMsg.Subject)
strFolderpath = enviro & "\Documents\" & strName & "\"

you'd add a line to add the date and time to the subfolder name:
strName = strName & Format(objMsg.ReceivedTime, "yyyymmdd-hhmmss")
for address, you'd add objmsg.senderemailaddress to it ( or & " " & objmsg.senderemailaddress)

1
0
Reply
Flavo
June 15, 2016 9:32 am

Hi , Diane How can I save a file include into a email by hyperlink?

0
0
Reply
Diane Poremsky
Author
Reply to  Flavo
June 15, 2016 10:40 am

you want to save an attachment and insert a link to the attachment in the original message? I have a macro here - https://www.outlook-tips.net/code-samples/save-and-delete-attachments/

0
0
Reply
Flavio
Reply to  Diane Poremsky
June 24, 2016 6:00 am

Hi Diane , thank you for your replay and useful code but i'll try to explain better (better than before) what i would like to do. I receive many e-mail with link . In this link is present the attachment , then if i click on it attachment start a window that ask if I want open or save(download) the real doc (it is often a pdf). I would like to create (if is possible) a macro that save automatically this kind of pseudo attachment file too. The other file's attached (txt,word,excel and so on) are saved by code that you posted here . Best Regards

0
0
Reply
Diane Poremsky
Author
Reply to  Flavio
June 24, 2016 11:29 pm

Ah. I have macros that will open the links but you'd need to use clickyes or a windows macro to respond to the open or save dialog (unless you choose never ask again). https://www.slipstick.com/developer/code-samples/open-hyperlinks-email-message/ will open the links (as long as the links are from the same domain, you could change the pattern so it only opens these links.)

1
0
Reply
Flavio
Reply to  Diane Poremsky
June 28, 2016 3:39 am

Thank you Diane you are an angel :-)

0
0
Reply

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

Latest EMO: Vol. 30 Issue 29

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
  • Jetpack plugin with Stats module needs to be enabled.
  • 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
  • New Outlook: Show To, CC, BCC in Replies
  • Insert Word Document into Email using VBA
  • Delete Empty Folders using PowerShell
  • Warn Before Deleting a Contact
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

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

New Outlook: Show To, CC, BCC in Replies

Insert Word Document into Email using VBA

Delete Empty Folders using PowerShell

Warn Before Deleting a Contact

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 © 2025 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