【问题标题】:Modifying Email Headers in Mailbox修改邮箱中的电子邮件标头
【发布时间】:2014-10-07 18:43:38
【问题描述】:

我在 Exchange 服务器的邮箱中有一大堆电子邮件,这些电子邮件源自 POP3 下载和转发应用程序 - 这意味着“已接收”日期戳反映了它被传递到 Exchange 的时间,而不是它发送到 Exchange 的时间。已发送(最多 3 周不等)。我知道您可以按发送日期进行过滤,但由于默认的 Outlook 视图是订购“接收日期”字段,而且我非常固执,我正在寻找一个完全向后的解决方案来解决我的问题。

我想更改“received on”标头信息以反映标头“Sent On”部分中的日期戳,然后将更改应用回邮箱。 目前我所能做的就是想出一种方法来通过 Powershell 读取标头信息,但无法写回它。

我对任何通过 PS 或 PHP 的方法持开放态度。

任何建议将不胜感激!

【问题讨论】:

    标签: php email powershell exchange-server


    【解决方案1】:

    您使用的是哪个版本的 Exchange?您可以使用 Exchange Web 服务访问服务器吗?如果可以,那么您应该能够访问发送和接收时间的扩展属性并在必要时对其进行修改,例如,如果发送和接收时间之间存在差异,则以下将枚举收件箱中的所有消息并修改接收日期超过 60 分钟

        ## Get the Mailbox to Access from the 1st commandline argument
    
    $MailboxName = $args[0]
    
    ## Load Managed API dll  
    
    ###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT
    $EWSDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services'|Sort-Object Name -Descending| Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll")
    if (Test-Path $EWSDLL)
        {
        Import-Module $EWSDLL
        }
    else
        {
        "$(get-date -format yyyyMMddHHmmss):"
        "This script requires the EWS Managed API 1.2 or later."
        "Please download and install the current version of the EWS Managed API from"
        "http://go.microsoft.com/fwlink/?LinkId=255472"
        ""
        "Exiting Script."
        exit
        }
    
    ## Set Exchange Version  
    $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2  
    
    ## Create Exchange Service Object  
    $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)  
    
    ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials  
    
    #Credentials Option 1 using UPN for the windows Account  
    $psCred = Get-Credential  
    $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())  
    $service.Credentials = $creds      
    
    #Credentials Option 2  
    #service.UseDefaultCredentials = $true  
    
    ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
    
    ## Code From http://poshcode.org/624
    ## Create a compilation environment
    $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
    $Compiler=$Provider.CreateCompiler()
    $Params=New-Object System.CodeDom.Compiler.CompilerParameters
    $Params.GenerateExecutable=$False
    $Params.GenerateInMemory=$True
    $Params.IncludeDebugInformation=$False
    $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null
    
    $TASource=@'
      namespace Local.ToolkitExtensions.Net.CertificatePolicy{
        public class TrustAll : System.Net.ICertificatePolicy {
          public TrustAll() { 
          }
          public bool CheckValidationResult(System.Net.ServicePoint sp,
            System.Security.Cryptography.X509Certificates.X509Certificate cert, 
            System.Net.WebRequest req, int problem) {
            return true;
          }
        }
      }
    '@ 
    $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
    $TAAssembly=$TAResults.CompiledAssembly
    
    ## We now create an instance of the TrustAll and attach it to the ServicePointManager
    $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
    [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
    
    ## end code from http://poshcode.org/624
    
    ## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use  
    
    #CAS URL Option 1 Autodiscover  
    $service.AutodiscoverUrl($MailboxName,{$true})  
    "Using CAS Server : " + $Service.url   
    
    #CAS URL Option 2 Hardcoded  
    
    #$uri=[system.URI] "https://casservername/ews/exchange.asmx"  
    #$service.Url = $uri    
    
    ## Optional section for Exchange Impersonation  
    
    #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 
    
    # Bind to the Inbox Folder
    $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)   
    $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
    
    $PR_MESSAGE_DELIVERY_TIME = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x0E06, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::SystemTime)
    $PR_CLIENT_SUBMIT_TIME = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x0039, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::SystemTime)
    
    $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)  
    $psPropset.Add($PR_CLIENT_SUBMIT_TIME)
    $psPropset.Add($PR_MESSAGE_DELIVERY_TIME)
    #Define ItemView to retrive just 1000 Items    
    $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)
    $ivItemView.PropertySet = $psPropset
    $fiItems = $null
    $type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
    $type = $type.MakeGenericType("Microsoft.Exchange.WebServices.Data.Item" -as "Type")
    $Items = [Activator]::CreateInstance($type)
    do{    
        $fiItems = $service.FindItems($Inbox.Id,$ivItemView)    
        foreach($Item in $fiItems.Items){      
            $ClientSubmitTime = $null
            $DeliveryTime = $null
            [Void]$Item.TryGetProperty($PR_CLIENT_SUBMIT_TIME,[ref]$ClientSubmitTime)
            [Void]$Item.TryGetProperty($PR_MESSAGE_DELIVERY_TIME,[ref]$DeliveryTime)
            if($ClientSubmitTime -ne $null -band $DeliveryTime -ne $null){
                $TimeSpan =  NEW-TIMESPAN –Start $ClientSubmitTime –End $DeliveryTime 
                $rptobj = "" | select Action,Subject,DELIVERY_TIME,SUBMIT_TIME,Diff
                $rptobj.Subject = $Item.Subject
                $rptobj.DELIVERY_TIME = $DeliveryTime
                $rptobj.SUBMIT_TIME = $ClientSubmitTime
                $rptobj.Diff = [Math]::Round($TimeSpan.TotalMinutes,0)
                if($TimeSpan.TotalMinutes -lt -60 -bor $TimeSpan.TotalMinutes  -gt 60 ){
                    $rptobj.Action = "Processing"
                    Write-Output $rptobj
                    $Item.SetExtendedProperty($PR_MESSAGE_DELIVERY_TIME,$ClientSubmitTime)
                    $Items.Add($Item)       
                }
                else{
                    $rptobj.Action = "Skip"
                    #Write-host ($rptobj)
                }           
            }
    
        }    
        $ivItemView.Offset += $fiItems.Items.Count    
    }while($fiItems.MoreAvailable -eq $true) 
    $BatchUpdateItems = [Activator]::CreateInstance($type)
    foreach($Item in $Items){
        $BatchUpdateItems.Add($Item)
        if($BatchUpdateItems.Count -ge 50){
            Write-Host ("Updating " + $BatchUpdateItems.Count)
            $Result = $null
            $Result = $service.UpdateItems($BatchUpdateItems,$SubFolder.Id,[Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverwrite,[Microsoft.Exchange.WebServices.Data.MessageDisposition]::SaveOnly,[Microsoft.Exchange.WebServices.Data.SendInvitationsMode].SendToNone)
            [INT]$collectionCount = 0
            [INT]$Rcount = 0  
            [INT]$Errcount = 0
            if($Result -ne $null){
                foreach ($res in $Result){ 
                    if ($res.Result -eq [Microsoft.Exchange.WebServices.Data.ServiceResult]::Success){  
                        $Rcount++  
                    } 
                    else{
                        $Errcount++
                    }
                    $collectionCount++
                }  
            }
            else{
                Write-Host -foregroundcolor red ("Update Result Null Exception")
            }
            Write-host ($Rcount.ToString() + " Items Updated Successfully " + "Total Processed " + $nmbProcessed + " Total Folder Items " + $Items.Count) 
            if($Errcount -gt 0){
                Write-Host -foregroundcolor red ($Errcount.ToString() + " Error failed Update")
            }
            $BatchUpdateItems.Clear()
        }
    }
    if($BatchUpdateItems.Count -gt 0){
            Write-Host ("Updating " + $BatchUpdateItems.Count)
            $Result = $null
            $Result = $service.UpdateItems($BatchUpdateItems,$SubFolder.Id,[Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverwrite,[Microsoft.Exchange.WebServices.Data.MessageDisposition]::SaveOnly,[Microsoft.Exchange.WebServices.Data.SendInvitationsMode].SendToNone)
            [INT]$collectionCount = 0
            [INT]$Rcount = 0  
            [INT]$Errcount = 0
            if($Result -ne $null){
                foreach ($res in $Result){ 
                    if ($res.Result -eq [Microsoft.Exchange.WebServices.Data.ServiceResult]::Success){  
                        $Rcount++  
                    } 
                    else{
                        $Errcount++
                    }
                    $collectionCount++
                }  
            }
            else{
                Write-Host -foregroundcolor red ("Update Result Null Exception")
            }
            Write-host ($Rcount.ToString() + " Items Updated Successfully " + "Total Processed " + $nmbProcessed + " Total Folder Items " + $Items.Count) 
            if($Errcount -gt 0){
                Write-Host -foregroundcolor red ($Errcount.ToString() + " Error failed Update")
            }
            $BatchUpdateItems.Clear()
    }
    

    干杯 格伦

    【讨论】:

      猜你喜欢
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-05
      • 2020-05-30
      • 2014-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多