Last active
January 6, 2022 22:09
-
-
Save kbhunut/e4a57b9ffe7f36c7b3332610c92f4693 to your computer and use it in GitHub Desktop.
Script to dump email from an exchange Mailbox using EWS. This is script from 2014
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Import-Module -Name 'C:\PowerShell\Modules\EWSModule\EWSModule.psm1' | |
###Requires -Modules EWSModule | |
function Get-cDumpMailboxEmail | |
{ | |
[CmdletBinding()] | |
Param( | |
[Parameter(Mandatory = $true, | |
Position = 0)] | |
$OutputPathRoot, | |
[pscredential] | |
$Credential = (Get-Credential) | |
) | |
Begin{ | |
$ErrorActionPreference = 'Stop' | |
if(!(Test-Path $OutputPathRoot)) | |
{ | |
Write-Error -Message 'Unable to Find OutputRoot - Check your path' | |
} | |
$lastDownload = $false | |
$lastDownloadID = $null | |
$foundEmail = $null | |
$lastCheckedFile = "C:\PowerShell\Logs\DumpLastChecked.txt" | |
$mailBox = '[email protected]' | |
$exchCasFQDN = 'mail.example.com' | |
if(Test-Path -Path $lastCheckedFile) | |
{ | |
$lastDownloadID = (Get-Content -Path $lastCheckedFile )[0] | |
$lastDownloadDate = Get-Date -Date (Get-Content -Path $lastCheckedFile)[1] | |
$aqsString = "received:>=$(Get-Date -Date $lastDownloadDate -Format g)" | |
$lastDownload = $true | |
Write-Verbose -Message "Last Checked Email: $lastDownloadID" | |
Write-Verbose -Message "Last Checked Date: $lastDownloadDate" | |
Write-Verbose -Message "AQS Query: $aqsString" | |
} | |
} | |
Process{ | |
$EWSService = Connect-EWS -Credential $Credential -CASFQDN $exchCasFQDN -ExchangeVersion Exchange2010_SP2 | |
if($lastDownload) | |
{ | |
$foundEmails = Search-EWS -EWSService $EWSService -MailBoxAddress $mailBox -AQS $aqsString -ViewLimit 1000 | |
} | |
else | |
{ | |
$foundEmails = Search-EWS -EWSService $EWSService -MailBoxAddress $mailBox -ViewLimit 1000 | |
} | |
#read oldest first | |
$firstRun = $true | |
for($i = $foundEmails.Length-1;$i -ge 0;$i--) | |
{ | |
#Weird Bug with EWS or PowerShell array?? | |
if($i -eq 0 -and $firstRun) | |
{ | |
$foundEmail = $foundEmails | |
} | |
else | |
{ | |
$foundEmail = $foundEmails[$i] | |
$firstRun = $false | |
} | |
#if($foundEmail.Id -eq $lastDownloadID) | |
#{ | |
# Write-Verbose -Message 'Hit the marker' | |
# break | |
#} | |
# RegEX Match 6 Digit EmployeeID in Email Subject | |
if([Regex]::Matches($foundEmail.Subject, '\b\d{6}\b').Count -eq 1) | |
{ | |
$emplId = [Regex]::Match($foundEmail.Subject, '\b\d{6}\b').Value | |
#check to see if $employeeID from email subject match with AD record | |
#if(Get-ADUser -Filter {EmployeeNumber -eq $emplId}){ | |
Write-Verbose -Message "Email Found - $($foundEmail.Subject)" | |
#Load Email Full Content. | |
$foundEmail.Load() | |
$recievedDateFormat = Get-Date -Date $foundEmail.DateTimeReceived -Format MM-dd-yyyy_HHmmss | |
#Create Folder Based on ID from Email subject | |
$folderPath = New-Folder -path $OutputPathRoot -folderName $emplId | |
#Massage FileName based on Subject and remove any special character | |
if($foundEmail.Subject -eq $null) | |
{ | |
$emailOutput = "$folderPath\No Subject ($recievedDateFormat).eml" | |
} | |
else | |
{ | |
#Replace \ character from Subject then set filename | |
if($foundEmail.Subject.Length -gt 15){ | |
$emailOutputPartitalName = $(($foundEmail.Subject -replace '[^a-zA-Z0-9_\(\)\- ]').Substring(0,15)) | |
}else{ | |
$emailOutputPartitalName = $($foundEmail.Subject -replace '[^a-zA-Z0-9_\(\)\- ]') | |
} | |
$emailOutput = "$folderPath\($recievedDateFormat) $emailOutputPartitalName.eml" | |
} | |
#Save Email Content Byte[] into File | |
if(!(Test-Path $emailOutput)) | |
{ | |
Write-Verbose -Message "Writing Email to Disk: $emailOutput" | |
#$foundEmail | | |
#Get-EWSEmailContentAsByte | Set-Content -Path $emailOutput -Encoding Byte | |
$propSet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent) | |
$foundEmail.load($propSet) | |
#$foundEmail.MimeContent.Content | Set-Content -Path $emailOutput -Encoding Byte | |
#$foundEmail | Get-EWSEmailContentAsByte | |
#$emlByte = $foundEmail | Get-EWSEmailContentAsByte | |
$fiFile = new-object System.IO.FileStream($emailOutput, [System.IO.FileMode]::Create) | |
$fiFile.Write($foundEmail.MimeContent.Content, 0, $foundEmail.MimeContent.Content.Length) | |
$fiFile.Close() | |
$fiFile.Dispose() | |
} | |
#Saving Attachment(s) | |
$attachments = Get-EWSAttachments -EmailMessages $foundEmail | |
foreach($attachment in $attachments) | |
{ | |
if(($attachment.Content) -ne $null){ | |
Write-Verbose -Message 'Attachment Found' | |
$fileNameSplit = $attachment.filename.Split('.') | |
$filenameExt = $fileNameSplit[$fileNameSplit.length-1] | |
$filenameWOext = $attachment.filename -Replace ".$filenameExt" | |
$attachmentOutput = "$folderPath\($recievedDateFormat) $filenameWOext.$filenameExt" | |
if(!(Test-Path $attachmentOutput)) | |
{ | |
Write-Verbose -Message "Write Attachment to Disk: $attachmentOutput" | |
$fiFile = new-object System.IO.FileStream($attachmentOutput, [System.IO.FileMode]::Create) | |
$fiFile.Write($attachment.Content, 0, $attachment.Content.Length) | |
$fiFile.Close() | |
} | |
} | |
} | |
#Write-Output -InputObject $foundEmail | |
#} | |
} | |
#Last Download/Check Marker | |
$lastCheckedEmail = "$($foundEmail.Id)`r`n$($foundEmail.DateTimeReceived)" | |
$lastCheckedEmail | Set-Content -Path $lastCheckedFile -Encoding Ascii -Force | |
Write-Verbose -Message "***Last Checked Email: $lastCheckedEmail" | |
} | |
} | |
} | |
function New-Folder | |
{ | |
param | |
( | |
[String] | |
$path, | |
[String] | |
$folderName | |
) | |
if(!(Test-Path -Path "$path\$folderName")) | |
{ | |
$newFolder = "$path\$folderName" | |
Write-Verbose -Message "Creating Folder $newFolder" | |
return (New-Item -Path $newFolder -ItemType Directory).ToString() | |
} | |
else | |
{ | |
return "$path\$folderName" | |
} | |
} | |
function Test-cDumpMailboxEmail | |
{ | |
Get-cDumpMailboxEmail -OutputPathRoot 'C:\PowerShell\TestFolder' -Credential (Import-Clixml -Path 'emailcred.xml') -Verbose | |
} | |
try{ | |
Get-cDumpMailboxEmail -OutputPathRoot '\\example\dumpEmails' -Credential (Import-Clixml -Path 'C:\PowerShell\Cred\cred.xml' ) -Verbose | |
}catch{ | |
Send-MailMessage -To '[email protected]' -From '[email protected]' -Subject 'Error with DumpMailbox' -Body "$error[0]" -SmtpServer smtp.example.local | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment