1
votes

I have a whole heap of emails sitting on my mailbox in an Exchange server that originated from a POP3 download and forward application - which means that the "Received" datestamp reflects the time that it was delivered to Exchange as opposed to when it was sent (which varies up to 3 weeks). I know that you can filter by send date but since the default outlook view is to order the "received on" field, and I'm incredibly stubborn I'm looking for a completely backwards solution to my issue.

I'd like to change the "received on" header information to reflect the datestamp in the "Sent On" part of the header and then apply the change back into the mailbox. At the moment all I've been able to do is come up with a way to read the header info via Powershell but have been unable to write back to it.

I'm open to any method via PS or PHP.

Any suggestions would be greatly appreciated!

1

1 Answers

0
votes

What version of Exchange are you using ? Can you access the server using Exchange Web Services ? if you can then you should be able to access the Extended properties for the Sent and Received Time and modify them if necessary eg the following would enumerate all the messages in the Inbox and modify the Received-date if the difference between the Sent and Received time is more then 60 minutes

    ## 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()
}

Cheers Glen