Get metadata from .msg files saved to local drive

Post number 12 has been selected as the best answer.

mail11

Senior Member
Outlook version
Email Account
IMAP
Operating system::    Windows 10
Outlook version:     365
Email type or host:    365

Hi
Firstly, is it possible to get metadata information from saved .msg files to local drive, in particular "Title".
And then would it possible to edit this using Visual Basic.

The intention was to include From and To in the Title field so you could see this in Windows Explorer, as shown below.

I think it may be possible to include From and To in the Name of the saved email, however because of restrictions on number of characters in Windows Explorer (256 I think), this won't be practical.

Please assist or send links to other topics which may be relevant.


1741487748085.png
 
This is a skeleton scaffolding I pulled from an old project to get you started. Needs lots of work for your specific case. Good luck.

Code:
Public Sub TEST_UpdateMsgFileNames()

    '   Setup to walk thru all the files in a Windows Folder
    '
    Dim FolderPath As String
    FolderPath = "C:\JUNK\UpdateMsgFileNames"
    
    Dim UpdatedFolderPath As String
    UpdatedFolderPath = "C:\JUNK\UpdatedMsgFileNames"
    
    Dim glbFSO As Scripting.FileSystemObject
    Set glbFSO = New Scripting.FileSystemObject
    
    Dim oFolder As Scripting.Folder
    Set oFolder = glbFSO.GetFolder(FolderPath)
    
    Dim oFiles As Scripting.Files
    Set oFiles = oFolder.Files

    '   For each file ...
    '
    Dim oFile As Scripting.File
    For Each oFile In oFiles
    
        '   Open the MSG file as an Outlook Object
        '
        Dim FilePath As String
        FilePath = oFile.Path
        
        Dim oItem As Outlook.MailItem
        Set oItem = Session.OpenSharedItem(FilePath)
        
        ' ---------------------------------------------------------------------
        '   Extract info from the oItem MailItem and build a NewFileName
        '
        '       Needs a lot of detail code here. To extract the info wanted in the
        '       NewFileName from the MailItem, check for invalid characters in NewFileName,
        '       maximum File Name lenght, ad nauseam.
        '
        ' ---------------------------------------------------------------------
        
        '   e.g. Build a ToList string from Recipients
        '
        Dim oRecipients As Outlook.Recipients
        Set oRecipients = oItem.Recipients
        
        Dim RecipientsArray() As String
        ReDim RecipientsArray(1 To oRecipients.Count)
        Dim RecipientsIndex As Long
        For RecipientsIndex = 1 To oRecipients.Count
            RecipientsArray(RecipientsIndex) = oRecipients.Item(RecipientsIndex).Name
        Next RecipientsIndex
        
        Dim ToList As String
        ToList = Join(RecipientsArray, " ; ")
        
        '   Build the new file name
        '
        Dim NewFileName As String
        NewFileName = "To = " & ToList
        
        '  Copy the file as NewFileName to a different directory
        '
        '       SPOS - Stupid caches files opened with OpenSharedItem and there
        '       is no sure fire way to make him let go. So we can't just Rename (Move)
        '       the original in place.
        '
        '       https://stackoverflow.com/questions/14439689/openshareditem-for-opening-msg-files-showing-error-in-outlook-c-sharp
        '
        oFile.Copy UpdatedFolderPath & "\" & NewFileName & ".msg"
        
    Next oFile

End Sub
 
Last edited:
You will need to add the "Microsoft Scripting Runtime" to your VBA References to run this code.

1741562387837.png
 
Here is a function set from my framework for cleaning up a file name string. You can incorporate into UpdateMsgFileNames if appropriate.

Code:
' =====================================================================
'   FileSpec Cleanup
' =====================================================================

'   Replace any Invalid Characters in a full FileSpec
'
Public Function File_CleanupFileSpec(ByVal Raw As String, Optional ByVal RepChar As String = "_") As String

    '   Cut and save the "C:" or "\\" prefix
    '
    Dim Prefix As String
    Prefix = Left(Raw, 2)
    Raw = Mid(Raw, 3)
    
    '   Cleanup the remaining FileSpec
    '
    Dim PathPieces As Variant
    PathPieces = Split(Raw, "\")
    Dim PieceIx As Long
    For PieceIx = 0 To UBound(PathPieces)
        PathPieces(PieceIx) = File_CleanupNameSegment(PathPieces(PieceIx), RepChar)
    Next PieceIx
    
    '   Put the pieces back together with the Prefix
    '
    File_CleanupFileSpec = Prefix & Join(PathPieces, "\")

End Function

'   Replace any Invalid Characters in a Piece of a FileSpec
'
'       NOT for a full File Spec. Only pieces after "C:" and between "/\"s.
'       See: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file
'       2024-10-29 - Added any Control Chars
'
Public Function File_CleanupNameSegment(ByVal Raw As String, Optional ByVal RepChar As String = "_") As String

    Dim Cooked As String
    Cooked = Raw
    
    '   Replace any Control Chars
    '
    Dim AscV As Long
    Dim LoopIx As Long
    For LoopIx = 1 To Len(Cooked)
        AscV = Asc(Mid(Cooked, LoopIx, 1))
        Select Case AscV
            Case 0 To 31, 127, 251 To 255
                Cooked = Replace(Cooked, Chr(AscV), RepChar)
            Case Else
            ' Continue
        End Select
    
    Next LoopIx
    
    '   Replace any Invalids
    '
    Dim Invalids As String
    Invalids = "<>:""/\|?*"

    For LoopIx = 1 To Len(Invalids)
        Cooked = Replace(Cooked, Mid(Invalids, LoopIx, 1), RepChar)
    Next LoopIx

    File_CleanupNameSegment = Cooked

End Function
 
Thanks Hornblower409, have been though the code and it's very useful.
My best attempt to extract Title metadata is shown below but it doesn't work ... get the error message:
Run-time error '-2147467259 (800004005)': Method 'NameSpace' of object 'IShellDispatch6' failed.

The function to get Title is based on Excel algorithm, maybe that's why it doesn't work, but could it be modified to suit .msg files in a folder.

Also, the question of metadata for .msg files. Is Title available at all? And can it be modified?

Diane, you say it can be changed? Please elaborate.

Code:
Option Explicit

Public Sub TEST_UpdateMsgFileNames()
    Dim FolderPath As String
    Dim glbFSO As Scripting.FileSystemObject
    Dim oFolder As Scripting.Folder
    Dim oFiles As Scripting.Files
    Dim oFile As Scripting.File
    Dim FilePath As String
    Dim file_name As String
    Dim my_title As String
   
    FolderPath = "C:\_test"

    Set glbFSO = New Scripting.FileSystemObject
    Set oFolder = glbFSO.GetFolder(FolderPath)
    Set oFiles = oFolder.Files

    For Each oFile In oFiles
        FilePath = oFile.Path
        file_name = Mid(FilePath, InStrRev(FilePath, "\") + 1)
        my_title = get_title(FilePath, file_name):
        MsgBox my_title
    Next oFile
End Sub

Function get_title(ByVal FilePath As String, ByVal file_name As String)
    Dim objFolder As Object, objFolderItem As Object
    Dim objShell As Object
    Dim file_name_Unicode As String, file_path_Unicode As String
    file_name_Unicode = StrConv(file_name, vbUnicode)
    file_path_Unicode = StrConv(FilePath, vbUnicode)
    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.NameSpace(StrConv(file_path_Unicode, vbFromUnicode))
    If Not objFolder Is Nothing Then
        Set objFolderItem = objFolder.ParseName(StrConv(file_name_Unicode, vbFromUnicode))
    End If
    If Not objFolderItem Is Nothing Then
        get_title = objFolder.GetDetailsOf(objFolderItem, 21) '21 is for Title
    End If
    Set objShell = Nothing
    Set objFolder = Nothing
    Set objFolderItem = Nothing
End Function
 
Mail11

I am sorry. I completely misunderstood your original question. I thought you wanted to extract information from the contents of the MSG files (i.e. the email stored in the file). Not from the Windows file name and attributes.
 
You need to get the msg properties - in a global variable - as you are saving the file then write it to the properties. I was testing one I found online and it didn't save the properties to the message - or they weren't showing up in file explorer. I was on the road and wasn't sure if it was because I was using parallels on my macbook (it's an ARM version of windows and can be weird) or the code. When I have a chance, I'll test it on my desktop.

But - as long as the code writes to the file system properties, code that works for Excel should work with a bit of tweaking. You need to get the field values before saving the message as a file.


Or maybe not... msg files don't have the same properties - I tried adding custom ones but the available list is not Title etc and the ones on the list aren't in the list of Explorer fields. You can type field names in - but they don't show in Explorer fields of the same name.
1741614618000.png

This is from a word doc - excel's is similar.
1741614602056.png
 
OK thanks Hornblower409 and Diane.

Or maybe not... msg files don't have the same properties
Diane, yes that's something that needs to be worked through.
The Title field doesn't show up when you right-click Properties/Details, neither do many other properties that would show up for Excel, Word or PDF files.
Thought that .msg have bee similar in some ways to .docx file.

Have you come across any information online that could assist?
 
Thanks Hornblower409 that was useful, it doesn't look promising.

Is changing to my original idea of extracting the data from the contents of the MSG files an option? What problem are you trying to solve?
I'm not quite sure what you mean by the first sentence, but in terms of extracting information (From, To), I was able to do that.
What I'm trying to do is to show the data from "From" and "To" somewhere other than the filename that can be seen in Windows Explorer (when in Details view). This is because there is a character limit with filenames in Windows Explorer (256 No. or similar), and even if there wasn't a limit, reading the email subject line I think is difficult for me. I save .msg files to local drive for information.
Using something like the Title field would have been perfect to store this data.

Please note I can't use or download software on computer, and prefer to do with Visual Basic.
 
I found a possible from Attach metadata to outlook msg file that is visible in Windows Explorer Details view?

It's the (very old) "DSO Ole Document Properties Reader 2.1" COM DLL. It's a single file that you put anywhere on your system and then add it to your VBA References:

1741666733627.png


Then you can use it to update selected attributes of a Windows file. "Author" and "Subject" work. I haven't tried all the others:

1741666901750.png


1741666937047.png


Code:
Sub TEST_UpdateMsgAttributes()

    UpdateMsgAttributes ("C:\Junk\UpdateMsgFileNames\Parking spot.msg")

End Sub

Sub UpdateMsgAttributes(msgFile As String)

    Dim objDSO As Object
    Dim objVariant As Variant
    Dim oNamespace As NameSpace
    Dim strAuthor As String
    Dim strSubject As String
    Dim item As Outlook.MailItem

    ' Open the msg in Outlook to get the attributes from the MailItem
    '     Use CreateItemFromTemplate instead of OpenSharedItem
    '     because OpenSharedItem puts a lock on the file, and the lock is only
    '     released at an indeterminate time after releasing the mailitem
    ' Set oNamespace = Application.GetNamespace("MAPI")
    ' Set objVariant = oNamespace.OpenSharedItem(msgFile)
    Set objVariant = Application.CreateItemFromTemplate(msgFile)

    If objVariant.Class = olMail Then
        Set item = objVariant
        strAuthor = item.SenderName
        strSubject = item.Subject
    End If
    objVariant.Close olDiscard
    Set objVariant = Nothing

    ' Reopen the msg with DSOFile to edit its attributes
    Set objDSO = CreateObject("DSOFile.OleDocumentProperties")
    objDSO.Open msgFile
    objDSO.SummaryProperties.Author = strAuthor
    objDSO.SummaryProperties.Subject = strSubject
    objDSO.Save

End Sub
 
Thanks Hornblower409, this looks like a big step forward.

I followed the steps in post #12, but am getting the error message below.
I can see that it's worked on your system.

Tried "On Error Resume Next" before this part of the code but no luck.


1741678166400.png
 
Do you have the "DSO Ole Document Properties Reader 2.1" file (dsofile.dll) on your system?
Did you add it to your VBA References?

1741666733627.png
 
Switch to Early Binding:

Replace the line:
Code:
Set objDSO = CreateObject("DSOFile.OleDocumentProperties")
With the two lines:
Code:
    Dim objDSO As DSOFile.OleDocumentProperties
    Set objDSO = New DSOFile.OleDocumentProperties
 
Thanks again, Hornblower409.
Yes I did all those things.

With the error message it was different this time.

1741743787621.png
 
This is the macro I was trying in a windows vm over the weekend... that did not do anything to the fields in the view. :(

Code:
  Dim sPath As String
  Dim sSubject As String
  Dim sSender As String

Public Sub SaveMessageAsMsg()
  Dim oMail As Outlook.MailItem
  Dim objItem As Object
  Dim sPath As String
  Dim dtDate As Date
  Dim enviro As String
  Dim sName As String
 
    enviro = CStr(Environ("USERPROFILE"))
   For Each objItem In ActiveExplorer.Selection
   If objItem.MessageClass = "IPM.Note" Then
    Set oMail = objItem
  
  sSender = oMail.SenderName
  sSubject = oMail.Subject
  ReplaceCharsForFileName sSubject, "-"
 
  dtDate = oMail.ReceivedTime
  sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, _
    vbUseSystem) & Format(dtDate, "-hhnnss", _
    vbUseSystemDayOfWeek, vbUseSystem) & "-" & sSubject & ".msg"
    
    sPath = enviro & "\Documents\" & sName
  Debug.Print sPath
  oMail.SaveAs sPath, olMsg
 
  End If
  Next
 
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, ":", 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

Sub UpdateFileProperties()
    Dim objShell As Object
    Dim objFolder As Object
    Dim objFolderItem As Object
    Dim filePath As String
    
    ' Specify the file path
    filePath = sPath
    Debug.Print filePath
    ' Create a Shell object
    Set objShell = CreateObject("Shell.Application")
    
    ' Get the folder containing the file
    Set objFolder = objShell.NameSpace(GetFolderPath(filePath))
    
    ' Get the file item
    Set objFolderItem = objFolder.ParseName(GetFileName(filePath))
    
    ' Update the file properties
    objFolderItem.ExtendedProperty("Title") = sSubject
    objFolderItem.ExtendedProperty("Client") = sSender
    objFolderItem.Save
    
    ' Clean up
    Set objFolderItem = Nothing
    Set objFolder = Nothing
    Set objShell = Nothing
    
    MsgBox "File properties updated successfully!"
End Sub

Function GetFolderPath(filePath As String) As String
    Dim pos As Integer
    pos = InStrRev(filePath, "\")
    GetFolderPath = Left(filePath, pos - 1)
End Function

Function GetFileName(filePath As String) As String
    Dim pos As Integer
    pos = InStrRev(filePath, "\")
    GetFileName = Mid(filePath, pos + 1)
End Function
--
 
Similar threads
Thread starter Title Forum Replies Date
G Save emails as msg file from Outlook Web AddIn (Office JS) Outlook VBA and Custom Forms 0
E Outlook 365 Save Selected Email Message as .msg File - oMail.Delete not working when SEARCH Outlook VBA and Custom Forms 0
E Save Selected Email Message as .msg File - digitally sign email doesn't works Outlook VBA and Custom Forms 1
R Saving Emails and Attachments as .msg file Using Outlook 3
S Problem Accessing .MSG Property 'ImageNaturalHeight' Tag '0x80010003' Outlook VBA and Custom Forms 1
J How to import many msg into different public folders in Outlook Outlook VBA and Custom Forms 7
N Save Selected Email Message as .msg File Outlook VBA and Custom Forms 12
G VBA to save selected Outlook msg with new name in selected network Windows folder Outlook VBA and Custom Forms 1
T vba extract data from msg file as attachment file of mail message Outlook VBA and Custom Forms 1
D Outlook 2016 Outlook Error Msg "The operation cannot be performed ..." How to Stop it Using Outlook 4
M Outlook 2016 msg attachments Using Outlook 0
R Sending email copy (*.msg file) of sent email if subject line contains specific string. Outlook VBA and Custom Forms 1
R Prompt asking the user to send email to folder as *.msg file Outlook VBA and Custom Forms 1
nathandavies Email Details to Excel & Save as .MSG on one macro - combination of 2 macros Outlook VBA and Custom Forms 3
J Outlook - 2013 - Error msg when copying folders from Online Archives to another user's mailbox Using Outlook 0
Diane Poremsky Save Selected Email Message as .msg File Using Outlook 11
I Outlook 2010, 2013 will not open .msg or .eml files Using Outlook.com accounts in Outlook 1
I Windows 10 - .msg files on disk show Explorer popup error Using Outlook 5
K Cannot consistently drag and drop .msg files into Outlook 2010 Using Outlook 0
Jessica .msg file saved in network drive appearing in Deleted Items folder Using Outlook 3
A Create message from .msg file Outlook VBA and Custom Forms 3
M Save selected email message as .msg file (with user to choose folder location) Outlook VBA and Custom Forms 14
M Can't open same msg file more than once at the same time in Outlook 2010 Using Outlook 7
Klaas "To Address" duplicated when moving msg to another folder Using Outlook 2
N Saving .msg as sent item on send Outlook VBA and Custom Forms 1
I Renamed msg file Using Outlook 3
F Cannot open extracted .msg files from outlook Outlook VBA and Custom Forms 1
A Moving .msg files back into outlook Using Outlook 2
B Outlook 2000 Rule to Move txt msg Not Working if size >24KB Using Outlook 3
A How to open .msg file from Hard disk folder? Using Outlook 3
P I am getting an error msg = cannot open file access denied Using Outlook 3
E Outlook 2007 Saves .MSG E-Mails with attachment from Public Folders as RTF Using Outlook 0
T Unable to open msg files in Outlook 2010 Using Outlook 11
E msg attachments lose their recipients "smtp" address Using Outlook 2
S OL 2007 user typing. into file box results in .htm.msg Using Outlook 5
J Saving Published Outlook Form as msg Using Outlook 1
G Outlook 2010 .msg Attachment Readability Using Outlook 1
O Lost attachment found but hidden in msg! Help!! Using Outlook 1
W Save all incomming and sent mails to folder on PC as .msg files Using Outlook 6
A Problems with moving msg files to network folder Using Outlook 3
F "MSG" type attachments are stripped away when senand previewed with HTML tags. Using Outlook 3
C Corrupt .msg file Using Outlook 1
S Outlook express 6.0 error msg Using Outlook 1
J HELP!Problem on Task, only half msg can view Using Outlook 7
D Assistance to create a mac that can move a msg based on category to spec fldr Using Outlook 1
J Code to Save Email as an .MSG to Directory when Emails Arrive Outlook VBA and Custom Forms 4
X Attached MSG files change when saved Outlook VBA and Custom Forms 1
B How to: Open .MSG File from Hard Drive via Code Outlook VBA and Custom Forms 2
H Save .msg attachment as .rtf Outlook VBA and Custom Forms 10
A Copy attached MSG to Inbox in IMAP folder Outlook VBA and Custom Forms 1

Similar threads

Back
Top