Reputation: 11
I need to write a powershell script that will go through an Outlook folder, pull out a uid from a URL in the email and send a GET with the uid in a new URL.
This is fine for emails that are just forwarded to the mailbox, but sometimes these are forwarded as attachments. I would like to open the .msg file to pull out the uid in the same way, but I can't find a way to do it without saving the file down first.
My initial idea was to save the file, open it, pull out the information, then delete the .msg. The problem is that Outlook keeps the instance of the .msg file open, so it cannot be deleted. I could do an $outlook.quit(), but then it will close the instance of Outlook that I'm using to go through the rest of the emails.
I'd prefer to not have to save every single .msg individually in a file and then interate through all of them if possible.
Is it possible to just read the body of the .msg file as if it's just another email message?
Here is my code:
# Mailbox name
$mailbox = "[email protected]"
# Name of folder containing reported phishing emails
$folderName = "SelfPhishTest"
# Create the Outlook object to access mailboxes
$Outlook = New-Object -ComObject Outlook.Application;
# Grab the folder containing the emails from the phishing exercise
$Folder = $Outlook.Session.Folders($mailbox).Folders.Item($folderName)
# Grab the emails in the folder
$Emails = $Folder.Items
# Path to save attachments to
$filepath = "C:\SavedPhishEmails\"
# Run through each email in the folder
foreach($email in $Emails){
# Output Sender Name for Testing
Write-Host $email.SenderName
# The number of email attachments
$intCount = $email.Attachments.Count
# If the email has attachments, let's open the .msg email
if($intCount -gt 0) {
# Let's go through those attachments
for($i=1; $i -le $intCount; $i++) {
# The attachment being looked at
$attachment = $email.Attachments.Item($i)
# If this is a .msg, let's open it
if($attachment.FileName -like "*.msg"){
$attachmentPath = $filepath+$attachment.FileName
$attachment.SaveAsFile($attachmentPath)
Get-ChildItem $attachmentPath |
ForEach-Object {
$msg = $Outlook.Session.OpenSharedItem($_.FullName)
$msg.Body
}
Remove-Item $attachmentPath
}
}
}
}
Upvotes: 0
Views: 1583
Reputation: 11
Figured it out.
Adding this will release the .msg file
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($msg) | Out-Null
Upvotes: 1