Search code examples
emailpowershell

How can I use Powershell to extract mail headers from .msg file?


I'm trying to write a script that reads the mail headers from a directory full of .msg files so I can later parse them via regex. I tried $MSG = Get-Content .\message.msg, which could work, but it's a pretty dirty output. Has anyone tried this? I can't seem to find a working example online.


Solution

  • You have a few options depending on your environment. If you are on a computer with Outlook installed you can easily do this with an Outlook com object. The problem is that the headers are not exposed by default so you have to dig for them.

    $ol = New-Object -ComObject Outlook.Application
    $msg = $ol.CreateItemFromTemplate("SOME\PATH\TO\A\MSG\FILE.msg")
    $headers = $msg.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E")
    $headers
    

    At this point you have a text block with all of the header information in it. If you want a specific header you will need to write a regex to extract it.

    You could also write a class that reads the raw content based on the specification. Or read in the raw content with powershell and write a regex to attempt to extract it.