2015-06-09 57 views
0

如何通過PowerShell中的EWS幫助將電子郵件保存在磁盤上?我搜索了互聯網,發現了一些answers,但這全部用於C#或VB。PowerShell EWS另存爲電子郵件

我現在有的代碼做了我需要的一切,將電子郵件複製到MS Outlook中的正確文件夾等,但我似乎無法弄清楚如何將郵件保存在文件夾中($ENV:Temp)在磁盤上。

這可以是EML或MSG格式,這對我無關緊要,但需要保存它的所有內容(正文,附件,From,To,..)。

我試過$Mail | Out-File "$env:TEMP\test.eml",它確實生成了一個15 KB的文件,但是當我用MS Outlook打開它時它似乎是空的。

謝謝你的幫助。

回答

0

在此期間,我找到了解決辦法:

$Service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList $ExchangeVersion 
$Service.Credentials = $Credentials.GetNetworkCredential() 
$Service.AutodiscoverUrl($BNLMailbox) 

Try { 
    $PowerShellPathId = Find-MailFolderIDHC @FindMailParams -Path $BNLMailboxInbox 
    $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($Service,$PowerShellPathId) 
} 
Catch { 
    # Exchange version not correct or path not found 
    throw "Move-MailsHC $($Global:Error[0].Exception.Message)" 
} 

$Props = [Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties 
$PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet($Props) 
$PropertySet.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text 
$PropertySet.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent) 

$Date = [Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived 
$TimeSpan = (Get-Date).AddHours(-$HoursAgo) 
$Filter = New-Object -TypeName Microsoft.Exchange.WebServices.Data.SearchFilter+IsGreaterThan -ArgumentList $Date,$TimeSpan 

$View = New-Object Microsoft.Exchange.WebServices.Data.ItemView(100) 
$View.OrderBy.add([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived, 
    [Microsoft.Exchange.WebServices.Data.SortDirection]::Ascending) 

foreach ($Mail in $Mails.Items) { 
    $TmpFolder = Join-Path $env:TEMP 'Move-MailsHC' 
    if (-not(Test-Path $TmpFolder)) { 
     New-Item $TmpFolder -ItemType Directory | Out-Null 
    } 
    Write-Verbose "Save original e-mail in temp '$TmpFolder'" 
    $TmpMail = Join-Path $TmpFolder 'Mail.eml' 
    $IoFile = New-Object System.IO.FileStream($TmpMail, [System.IO.FileMode]::Create) 
    $IoFile.Write($Mail.MimeContent.Content, 0, $Mail.MimeContent.Content.Length) 
    $IoFile.Close() 

    Write-Verbose "Download e-mail attachments to temp '$TmpFolder'" 
    foreach ($A in $Mail.Attachments){ 
     $A.Load() 
     $fiFile = New-Object System.IO.FileStream((Join-Path $TmpFolder $A.Name.ToString()), [System.IO.FileMode]::Create) 
     $fiFile.Write($A.Content, 0, $A.Content.Length) 
     $fiFile.Close() 
     Write-Verbose "Downloaded Attachment: $($A.Name.ToString())" 
    } 
}