Skip to content

Instantly share code, notes, and snippets.

@karbomusic
Created September 10, 2020 18:37
Show Gist options
  • Save karbomusic/8c7219dadd9459a527d3918d82a3a05c to your computer and use it in GitHub Desktop.
Save karbomusic/8c7219dadd9459a527d3918d82a3a05c to your computer and use it in GitHub Desktop.
Testing EWS Streaming Notifications
###########################################################
# Streaming Notifications Test
# Date: 4.26.18
# Requires EWS Managed API 2.2
# For Testing only, not fully vetted - could have issues.
# Defaults to inbox/newmailevent
###########################################################
param(
[Parameter(Mandatory=$true)]
[string]$EWSUri,
[Parameter(Mandatory=$true)]
[string]$EmailAccount,
[Parameter()]
[string]$IgnoreCertErrors=$true
)
Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
# Ignore cert errors
add-type @"
using System.Net;git
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public static class CertificateUtils {
public static bool TrustAllCertsCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
return true;
}
public static void TrustAllCerts() {
ServicePointManager.ServerCertificateValidationCallback = CertificateUtils.TrustAllCertsCallback;
}
}
"@
# Ignore cert errors if set
if($IgnoreCertErrors) {[CertificateUtils]::TrustAllCerts()}
$EWS = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1);
$EWS.Credentials = Get-Credential
$EWS.AutodiscoverUrl($EmailAccount);
$fldArray = new-object Microsoft.Exchange.WebServices.Data.FolderId[] 1
$Inboxid = new-object Microsoft.Exchange.WebServices.Data.FolderId ([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox, $MailboxName)
$fldArray[0] = $Inboxid
$stmsubscription = $EWS.SubscribeToStreamingNotifications($fldArray, [Microsoft.Exchange.WebServices.Data.EventType]::NewMail)
$stmConnection = new-object Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection($EWS, 30);
$stmConnection.AddSubscription($stmsubscription)
Register-ObjectEvent -inputObject $stmConnection -eventName "OnNotificationEvent" -Action {
foreach($notEvent in $event.SourceEventArgs.Events){
[String]$itmId = $notEvent.ItemId.UniqueId.ToString()
$message = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind($event.MessageData,$itmId)
"Subject : " + $message.Subject + " " + (Get-Date) | Out-File c:\temp\log2.txt -Append
}
} -MessageData $EWS
Register-ObjectEvent -inputObject $stmConnection -eventName "OnDisconnect" -Action {$event.MessageData.Open()} -MessageData $stmConnection
$stmConnection.Open()
Write-Host "Connection closed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment