powershell-open .msg附件没有保存

时间:2018-06-04 14:23:56

标签: powershell outlook email-attachments msg

我需要编写一个PowerShell脚本,该脚本将通过Outlook文件夹,从电子邮件中的URL中提取uid,并在新URL中发送带有uid的GET。

这适用于刚转发到邮箱的电子邮件,但有时会将这些电子邮件作为附件转发。我想以同样的方式打开.msg文件以取出uid,但我无法在不先保存文件的情况下找到方法。

我最初的想法是保存文件,打开文件,提取信息,然后删除.msg。问题是Outlook保持.msg文件的实例打开,因此无法删除。我可以做一个$ outlook.quit(),但是它会关闭我用来浏览其余电子邮件的Outlook实例。

我更喜欢不必在文件中单独保存每个单独的.msg,如果可能的话,然后在所有文件中进行交互。

是否可以只读取.msg文件的正文,就像它只是另一封电子邮件一样?

这是我的代码:

# Mailbox name
$mailbox = "abuse@place.com"
# 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
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

想出来。

添加此项将释放.msg文件

[System.Runtime.InteropServices.Marshal]::ReleaseComObject($msg) | Out-Null