Vijay Vijay - 3 months ago 58
PowerShell Question

Save Email as .MSG to Local Folder using Powershell

I have created a rule to move emails from inbox to subfolder "Task" .I am able to move the all emails from subfolder "Task" to another subfolder "Complete" in outlook but can anyone assist me in copying the emails as .msg file locally to a pre-defined folder.Below is the powershell code.

$olFolderInbox = 6;
$GetOutlook = New-Object -com "Outlook.Application";
$olName = $GetOutlook.GetNamespace("MAPI")
$olxEmailFolder = $olName.GetDefaultFolder($olFolderInbox)

$SubFolders = $olxEmailFolder.Folders | ? { $_.Name -match 'Tasks' };
$TargetFolder = $olxEmailFolder.Folders.Item('Completed')

$SubFolders.Items |

ForEach-Object -Process {
$psitem.Move($TargetFolder)


}

Answer

I am unsure if you can save an email to a .msg, however, you can save it as a .htm using the modified code

$olFolderInbox = 6
Add-Type -assembly 'Microsoft.Office.Interop.Outlook'
$GetOutlook = New-Object -ComObject 'Outlook.Application'
$olName = $GetOutlook.GetNamespace('MAPI')
$olxEmailFolder = $olName.GetDefaultFolder($olFolderInbox)

$SubFolders = $olxEmailFolder.Folders | Where-Object -FilterScript {
  $_.Name -match 'Tasks' 
}
$TargetFolder = $olxEmailFolder.Folders.Item('Completed')

$SubFolders.Items |    
ForEach-Object -Process {
  $psitem.HTMLBody | Set-Content C:\test\email.htm
  $psitem.Move($TargetFolder)
}