b5000
b5000

Reputation: 11

Save Email body to html file powershell

I am trying to convert a folder full of MSG files to HTML files. I have a scrip that gets most of the way there, but instead of displaying the text in powershell I need it to save each one as an individual html file. For some reason I can't get the save to work. I've tried various options like out-file and $body.SaveAs([ref][system.object]$name, [ref]$saveFormat)

$saveFormat = [Microsoft.Office.Interop.Outlook.olSaveAsType]::olFormatHTML
Get-ChildItem "C:\MSG\" -Filter *.msg |
    ForEach-Object {
        $body = ""
        $outlook = New-Object -comobject outlook.application
        $msg = $outlook.Session.OpenSharedItem($_.FullName)
        $body = $msg | Select body | ft -AutoSize
    }

Any advice on how to save this as individual files would be great.

Upvotes: 1

Views: 2786

Answers (1)

TheMadTechnician
TheMadTechnician

Reputation: 36277

To start with, you should not capture the output of a Format-* cmdlet in a variable. Those are designed to output to something (screen, file, etc).

Ok, that aside, you are already opening the msg files, so you just need to determine a name and then output the HTMLBody property for each file. Easiest way would be to just tack .htm to the end of the existing name.

Get-ChildItem "C:\MSG\*" -Filter *.msg |
    ForEach-Object {
        $body = ""
        $outlook = New-Object -comobject outlook.application
        $msg = $outlook.Session.OpenSharedItem($_.FullName)
        $OutputFile = $_.FullName+'.htm'
        $msg.HTMLBody | Set-Content $OutputFile
    }

Upvotes: 1

Related Questions