How to save all email attachments from Outlook msg files

I’ve recently been sent hundreds of emails saved as msg files which I needed to extract and save all of the attachments so they could be processed. Opening each message individually in Outlook and saving the attachments would of taken a month of Sundays. So instead I wrote the following powershell script.

param([string]$msgpath = [System.IO.Directory]::GetCurrentDirectory(), [string]$savepath = [System.IO.Directory]::GetCurrentDirectory() )
$outlook = new-object -comobject outlook.application
$msgs = get-childitem $msgpath -filter *.msg

foreach ($msg in $msgs)
{
	
	if ($msg.exists -eq $true) {
	write-host "opening message:" $msg
	$Omsg = $outlook.CreateitemFromTemplate($msgpath+$msg)
	$Omsg.attachments|foreach {
		$_.saveasfile((join-path $savepath $_.filename))
	}
	}
}

The script accepts 2 input parameters msgpath and savepath. msgpath is the path to the saved msg files. savepath is the path to save the attachments to. Both parameters default to the current working directory if they aren’t supplied.

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Twitter
  • Google Bookmarks

2 thoughts on “How to save all email attachments from Outlook msg files

  1. Thanks for this code,

    Do you know how to amend the script so that it saves multiple excel files? I run it and it only extracts 1 file per extension inside the .msg.

    Also, can it be modified to save a file if the filename already exists? e.g a previous .msg file saved filename.xls and the next .msg file has the same “filename.xls”? can a 1 be added? e.g “filename1.xls” “filename2.xls”

    Apologies for the quetions, my Powershell knowledge is poor to say the least.
    Regards.

Leave a Reply

Your email address will not be published. Required fields are marked *

*