如何使用PowerShell和EWS将邮件消息导出到EML或MSG文件

时间:2017-03-07 16:47:17

标签: powershell exchangewebservices exchange-server-2010 eml

我目前正在开发一个PowerShell脚本,需要从特定邮箱中提取所有邮件,如.eml或.msg文件,并将它们保存在备份服务器上。我正在使用PowerShell版本5和Exchange 2010管理控制台模块(EWS)。

目前,我的脚本能够访问收件箱文件夹中的所有邮件及其属性,例如正文,主题,附件等。但是,我找不到一种简单的方法或方法来导出消息(带有附件)。所以我的问题是,Exchange 2010中的EWS是否提供了从邮箱中提取/保存邮件的方法?

这是我的剧本:

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind
$service.AutodiscoverUrl($aceuser.mail.ToString())

$MailboxName = get-mailbox -Identity myMailBox@myWorkPlace.com

$folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName.PrimarySmtpAddress.ToString())
$rootfolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service, $folderidcnt)


$offset = 0;
$view = new-object Microsoft.Exchange.WebServices.Data.ItemView(10000, $offset)

$response = $service.LoadPropertiesForItems($results, [Microsoft.Exchange.WebServices.Data.PropertySet]::FirstClassProperties)

foreach ($mail in $results){

if ($mail.ToString() -eq "Microsoft.Exchange.WebServices.Data.EmailMessage"{
    **"Function to export this message an an .eml or .msg file on a remote shared folder"**
     }
}

1 个答案:

答案 0 :(得分:1)

代码的最后一部分必须是:

if ($mail.ToString() -eq "Microsoft.Exchange.WebServices.Data.EmailMessage") {
    $mailSubject = $mail.Subject
    $mailProps = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent)
    $mail.Load($mailProps)
    #TODO: clean up $mailSubject so it's filesystem friendly
    $fStream = New-Object System.IO.FileStream("C:\Temp\$mailSubject.eml", [System.IO.FileMode]::Create)
    $fStream.Write($mail.MimeContent.Content, 0, $mail.MimeContent.Content.Length)
    $fStream.Close()
}

$mailSubject = $mail.Subject在我们加载电子邮件之前抓取主题(主题然后“丢失”)。

$mail.Load($mailProps)加载电子邮件&amp;哑剧内容。

最后3条$fStream行将mime内容写入流。

当然,您需要添加一些规则来清理主题,或者以不同方式命名电子邮件。