A visitor to OutlookForums saves messages as text files and was tired of changing the default Save as format to txt.
I save multiple messages everyday as text files. I just upgraded from 2007 outlook to 2010. Before the upgrade I had it defaulted to save as text. I did not do this that I recall it just has been that way. Now that I have upgraded it is defaulted to msg. Please tell me if there is a way to do this as it will save me an immense amount of excess clicking.
This macro is a manual version of E-Mail: Save new items immediately as files. Unlike the original macro, which saves all new messages as text file, you need to select a message and run this macro to save it as a text file.
For other options and utilities, see How to Save Email in Windows File System.
Save selected message as a text file
A version of this macro which saves all selected messages as multiple individual text files is at SaveSelectedMailAsTxtFile. The code sample at SaveSelectedMailBodiesTxtFiles is the modification discussed in this comment and reply.
Sub SaveMailAsFile()
Const OLTXT = 0
Dim oMail As Outlook.mailItem
Dim sPath As String
Dim dtDate As Date
Dim sName As String
Set oMail = Application.ActiveExplorer.Selection.Item(1)
sName = oMail.Subject
ReplaceCharsForFileName sName, "_"
dtDate = oMail.ReceivedTime
sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, _
vbUseSystem) & Format(dtDate, "-hhnnss", _
vbUseSystemDayOfWeek, vbUseSystem) & "-" & sName & ".txt"
oMail.SaveAs "C:\path\to\save\" & sName, OLTXT
End Sub
Private Sub ReplaceCharsForFileName(sName As String, _
sChr As String _
)
sName = Replace(sName, "/", sChr)
sName = Replace(sName, "\", sChr)
sName = Replace(sName, ":", sChr)
sName = Replace(sName, "?", sChr)
sName = Replace(sName, Chr(34), sChr)
sName = Replace(sName, "<", sChr)
sName = Replace(sName, ">", sChr)
sName = Replace(sName, "|", sChr)
End Sub
Save selected messages to a single text file
This code sample saves the selected messages in one text file, replicating Outlook's behavior when you select multiple messages and choose Save as. It uses the current date and folder name as the file name and saves it to the user's My Documents folder.
Sub MergeSelectedEmailsIntoTextFile()
'From http://slipstick.me/fraz6
Dim objFS As New Scripting.FileSystemObject, objFile As Scripting.TextStream
Dim objItem As Object, strFile As String
Dim Folder As Folder
Dim sName As String
' Use your User folder as the initial path
Dim enviro As String
enviro = CStr(Environ("USERPROFILE"))
If ActiveExplorer.Selection.Count = 0 Then Exit Sub
' use the folder name in the filename
Set Folder = Application.ActiveExplorer.CurrentFolder
' add the current date to the filename
sName = Format(Now(), "yyyy-mm-dd")
' The folder path you use needs to exist
strFile = enviro & "\Documents\" & sName & "-" & Folder & ".txt"
Set objFile = objFS.CreateTextFile(strFile, False)
If objFile Is Nothing Then
MsgBox "Error creating file '" & strFile & "'.", vbOKOnly + vbExclamation _
, "Invalid File"
Exit Sub
End If
For Each objItem In ActiveExplorer.Selection
With objFile
.Write vbCrLf & "--Start--" & vbCrLf
.Write "Sender: " & objItem.Sender & " <" & objItem.SenderEmailAddress & ">" & vbCrLf
.Write "Recipients : " & objItem.To & vbCrLf
.Write "Received: " & objItem.ReceivedTime & vbCrLf
.Write "Subject: " & objItem.Subject & vbCrLf & vbCrLf
.Write objItem.Body
.Write vbCrLf & "--End--" & vbCrLf
End With
Next
objFile.Close
MsgBox "Email text extraction completed!", vbOKOnly + vbInformation, "DONE!"
Set objFS = Nothing
Set objFile = Nothing
Set objItem = Nothing
End Sub
Replace the code between strFile = enviro... and objFile.close with the following. To add more fields, add more objFile.Write lines.
strFile = enviro & "\Documents\" & sName & "-" & Folder & ".txt"
Set objFile = objFS.OpenTextFile(strFile, ForAppending, True)
For Each objItem In ActiveExplorer.Selection
objFile.Write (objItem.Body)
Next
objFile.Close
Super short code
This code is super short and works on the currently open or selected message only. You'll need to GetCurrentItem function to use this macro. You'll need to add a check mark to the Microsoft Scripting Runtime in Tools, References.
Messages are appended to one file.
Public Sub SaveEmailBody()
Dim objMail As MailItem
Dim fso As New FileSystemObject
Dim ts As TextStream
' get the function athttp://slipstick.me/e8mio
Set objMail = GetCurrentItem()
Set ts = fso.OpenTextFile("E:\Documents\mailfile.txt", ForAppending, True)
ts.Write (objMail.Body)
ts.Close
Set ts = Nothing
Set fso = Nothing
End Sub
Hubert says
Dear Ms.Diane,
I use the script described above, but it stops working when a graphic appears in the email. I have already checked the Outlook settings and enabling the option:
<<Read all standard mail in plain text>>
does not help. The whole thing is converted to text, but the graphics stay as they were.
The error when executing the script appears in the line of code:
Write objItem.Body
and the error message is:
Run-time error '5':
Invalid procedure call or argument.
Is there a solution for this, or can the text content of the email be written to a text file despite the graphics that occur?
I kindly ask for support.
An example of a graphic that stops the script and causes an error.
?
Best regards.
Hubert
Kumaresan says
Can anybody have a video for this task..If so please share it
Pat J says
Hi Diane,
Maybe I missed it but is there a setting I can set to allow me to default to .txt when saving a message as a file or possibly saving as last format used?
Diane Poremsky says
You didn't miss anything - its not an option. Sorry.
Sarmistha says
Hi Diane,
I am working on creating email from an Outlook template (.oft) file. The same has FomatText property as 'HTML'. The template is used to insert an image & necessary body (which includes tables; bullet points). I am facing issues with NewMessage.saveAs(path\filename&".msg", olMsg) statement. The issue is that it saves the filename.msg as plain 'TEXT'. The image is not visible and none of the formats i.e. bullets/table are visible. If I place NewMessage.display before/after 'saveAs' statement I can see the email generated as required i.e. with HTML content intact.
Can you please help me with suggestions as to what is going wrong in above line.
Meg says
Hi Diane, I have been using your code "Save selected message as a text file", but I want to save each email received and not the selected. you could help me? I understand this part define here "Set Omail = Application.ActiveExplorer.Selection.Item (1)" ?
Frank says
First of all, thank you verry mutch. I have been using your code to save all mails in a selection as text file. I only have one problem that i can't solve. If i run the macro on Outlook 2010, there is no problem. But i still have one system that works with Outlook 2003 and for some reason, the macro stops after 50 messages, no mather what the selection is
Neha says
Hi, I want to save all the mails from the same day with their date, is there a way to select mails with the current date in the vb script and then use those selected emails as above ?
Diane Poremsky says
I'm not sure what you want to do - the macro adds the received date to the saved file subject.
Mohan says
Hi Diane, thanks for the code, I'm using this code in outlook 2013 after building the rule from specific email address and using run script option. Only caveat is that I have to always select an email and run the rules to save that email to .txt file, is there a way that script can run automatically and save all the emails from that particular email address to .txt file. Thanks in advance for your reply.
Vivek Gupta says
Hi Diane,
Thanks for your code, very helpful! It has gotten me about halfway to my goal but hoping you can help me with the rest. I want to save all emails as they come into a specific folder as text files. The folder is at the same level as my Inbox folder. Do you mind explaining me how to do this? I'm new to VBA so all examples and explanations are very appreciated.
Diane Poremsky says
This will get you a folder at the same level as the inbox
Set myfolder = Session.GetDefaultFolder(olFolderinbox).Parent.Folders("folder name")
Vivek Gupta says
Thanks Diane! For some reason, the code I'm working with still doesn't work. Can you find anything wrong with the VBA below? The goal of the code is to take all emails going to the Picklists folder to save as text files to my USQ Text Files folder.
Sub Application_Startup()
Dim Ns As Outlook.NameSpace
Set Ns = Application.GetNamespace("MAPI")
Set Items = Ns.GetDefaultFolder(olFolderInbox).Items
Set myFolder = Session.GetDefaultFolder(olFolderInbox).Parent.Folders("Picklists")
End Sub
Sub Items_ItemAdd(ByVal Item As Object)
If TypeOf Item Is Outlook.MailItem Then
SaveMailAsFile Item
End If
End Sub
Sub SaveMailAsFile(oMail As Outlook.MailItem)
Dim dtDate As Date
Dim sName As String
Dim sFile As String
Dim sExt As String
sPath = "\antdeptPrimeNow3PAcctMgmtNYCUSQ Text Files"
sExt = ".txt"
sName = oMail.Subject
ReplaceCharsForFileName sName, "_"
dtDate = oMail.ReceivedTime
sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, _
vbUseSystem) & Format(dtDate, "-hhnnss", _
vbUseSystemDayOfWeek, vbUseSystem) & "-" & sName & sExt
oMail.SaveAs sPath & sName, olSaveAsMsg
End Sub
Sub ReplaceCharsForFileName(sName As String, _
sChr As String _
)
sName = Replace(sName, "/", sChr)
sName = Replace(sName, "", sChr)
sName = Replace(sName, ":", sChr)
sName = Replace(sName, "?", sChr)
sName = Replace(sName, Chr(34), sChr)
sName = Replace(sName, "", sChr)
sName = Replace(sName, "|", sChr)
End Sub
Diane Poremsky says
I think it's this -
Set Items = Ns.GetDefaultFolder(olFolderInbox).Items
Set myFolder = Session.GetDefaultFolder(olFolderInbox).Parent.Folders("Picklists")
This line: Sub Items_ItemAdd(ByVal Item As Object) is looking for the objects defined as items - which is the inbox.
Change those two lines to this and try it.
Set Items = Ns.GetDefaultFolder(olFolderInbox).Parent.Folders("Picklists").Items
Vivek Gupta says
Thank you once again! I'm clicking play in VBA to run this macro and see no results, nothing happens. I've used the SaveSelectedMailAsTxtFile macro before so I know the trust setting are enabled. Not sure why I can't see any results in my folder path. Do you have any idea?
Sanford E. Gerber says
Thanks for nothing. I asked a question and got a lot of computer gobbeldy-gook. Just answer the question.
Diane Poremsky says
Sorry, I don't see what question you asked to know how I could have answered it better.
kiwi says
Hi Diane,
I was trying your macro Save selected message as a text file. I managed to use successfully but couldn't quite get it to work to my needs.
I wanted it to run off a rule and only if the incoming email subject line contained certain text and then i wanted to move to a processed folder.
Does the macro have to contain the script steps for specific subject line words or can this be done from the rule likewise the moving to specified folder?
Between Outlooks create rule and your macro I wasn't quite able to get all 3 working automatically and correctly.
Please help
Thanks
Diane Poremsky says
A rule can contain the conditions but all actions should be in the script - so the rule can filter the subject, but the moving needs to be in the script.
Right before End sub add one of these lines:
'folder at the same level as inbox:
oMail.Move Session.GetDefaultFolder(olFolderInbox).Parent.Folders("Folder name")
subfolder under inbox:
oMail.Move Session.GetDefaultFolder(olFolderInbox).Folders("Folder name")
Cute_Flower says
> Did you check the Macro security settings?
There's absolutely nothing in the article about a "security setting".
Do you mean the "reference"?
Diane Poremsky says
The pages under code samples are mostly just code samples and assume the user knows the basics of using macros.
You need to have macro security set to Low during testing: https://www.slipstick.com/developer/how-to-use-outlooks-vba-editor/
Depending on which macro you use, you'll also need to set the reference to the file syncing object. From the page: You'll need to add a check mark to the Microsoft Scripting Runtime in Tools, References.
Simon Lukes says
Thank you so much - the code which saves all selected messages as multiple individual text files saved me literally hours of work.
Ramesh Govindarajan says
Wow, Ma'am. You are amazing. Thank you so much!!
Worked like a champ.
Diane Poremsky says
Ok - try this code - it's the modification above https://www.slipstick.com/files/SaveSelectedMailBodiesTxtFiles.txt
You'll need to add a checkmark the the microsoft scripting runtime in tools, references to use it.
Ramesh Govindarajan says
Hi Diane,
I'm using this code though -
https://www.slipstick.com/files/SaveSelectedMailAsTxtFile.txt
This does not separate them out, so I'm not sure how to extract just the body from the email. All it says is -
oMail.SaveAs "C:\Users\Diane\Dropbox\For EMO\" & sName, OLTXT
The reason I like this is because each email goes to a separate text file.
Thank you.
Diane Poremsky says
You want each message into its own text file?
add this to the top, under the other dim's
Dim fso As New FileSystemObject
Dim ts As TextStream
Replace the end of that macro with this - starting with the line i have here - you need to go to tools, references and add a check to microsoft scripting runtime. Then select some messages and run. This creates one text file per message.
sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, _
vbUseSystem) & Format(dtDate, "-hhnnss", _
vbUseSystemDayOfWeek, vbUseSystem) & "-" & sName & ".txt"
Set ts = fso.OpenTextFile("C:\Users\Diane\Dropbox\" & sName, ForAppending, True)
ts.Write (oMail.Body)
ts.Close
Next
Set ts = Nothing
Set fso = Nothing
end sub
Ramesh Govindarajan says
Thank you. I'm no good at coding, so I understand vaguely what you're saying, but have no clue how to do it.
So, I appreciate you adding the code here.
Thanks again.
Ramesh Govindarajan says
Hi there Diane,
Thank you for the script. I am able to use this - https://www.slipstick.com/files/SaveSelectedMailAsTxtFile.txt - in Outlook 2010 successfully.
One question though - this script basically extracts the entire email. Is there a way to just get the body out of the email and none of the header or subject information?
Thank you for your assistance!
Diane Poremsky says
You can get just the body but need to do it a little differently as you can't use Saveas. You'll need to grab the oMail.body: strBody = oMail.body then write it to a text file.
I'll add the code to this page.
Diane Poremsky says
Actually, the last macro - MergeSelectedEmailsIntoTextFile - already does it. Remove the lines that add the subject etc.
.Write "Recipients : " & objItem.To & vbCrLf
.Write "Received: " & objItem.ReceivedTime & vbCrLf
.Write "Subject: " & objItem.Subject & vbCrLf & vbCrLf
Or, replace the block between strfile and objfile.close with this- this will add mail to the current file.
strFile = enviro & "\Documents\" & sName & "-" & Folder & ".txt"
Set objFile = objFS.OpenTextFile(strFile, ForAppending, True)
For Each objItem In ActiveExplorer.Selection
objFile.Write (objItem.Body)
Next
objFile.Close
danni says
I'm most interested in the first of these. I managed to get it to work in Outlook 2010, but not in 2013. Is there anything that might be different for 2013?
Diane Poremsky says
What happens when you try it in Outlook 2013? (It should work.)
danni says
Nothing. I click, nothing happens visually, I go look at the folder where I expect the file to be but there's nothing there.
In 2010: I click, nothing happens visually, but the file does appear in the folder where I expect it to be.
Not to worry. Must be me doing something wrong.
Diane Poremsky says
Did you check the Macro security settings?
danni says
Yep, first thing I did. It's set to allow.
But I'm in a corporate environment, with group policies applied, and the 2013 client I tried it on probably has a different lock-down than my machine. Either that or it's PEBCAK :)
Thanks for responding.
Diane Poremsky says
It could be policy or user error or something else... here it failed because someone (who shall remain nameless) did not change the file path and C:\path\to\save does not exist on the computer. :)
You can test to see if it is working at all by adding a msgbox "line 1" at the top of the code and msgbox sName after each line that calls sname. - if you don't get the message boxes, the macro is not running at all. Debug.print would work too... or step into (F8) the macro and see if it hits all the lines.