≡ Menu

How to use a Proxy Server with the EWS Managed API and PowerShell

You might work in an environment where all web traffic must go through an outbound web proxy. Of course, this can add some complexity when it comes to writing EWS scripts that target an external Exchange organization, such as a partner or a hosted platform like Exchange Online available through Office 365. Luckily, EWS supports the use of a web proxy, and this can be set via the ExchangeService object. Let’s take a look at a couple of examples.

First, create an instance of the System.Net.WebProxy class, and set the URI for the proxy:

$proxy = new-object System.Net.WebProxy('http://tmg:8080')

Next, you can set the required user name and password on the $proxy object using the Credentials property, or you can use your logged on Windows credentials by setting the UseDefaultCredentials property to $true:

$proxy.UseDefaultCredentials = $true

Finally, assign your proxy object to the WebProxy property of your ExchangeService object:

$service.WebProxy = $proxy

Here’s some code that uses the EWS Managed API 1.1 to send an e-mail message from an Exchange Online mailbox, with all of the web service operations going through an outbound proxy server:

Add-Type -Path 'C:\Program Files\Microsoft\Exchange\Web Services\1.1\Microsoft.Exchange.WebServices.dll'
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList Exchange2010_SP1
$service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials -ArgumentList  'user@yourdomain.onmicrosoft.com', 'P@ssw0rd'

$proxy = new-object System.Net.WebProxy('http://tmg:8080')
$proxy.UseDefaultCredentials = $true
$service.WebProxy = $proxy

$service.AutodiscoverUrl('user@yourdomain.onmicrosoft.com', {$true})

$message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service
$message.Subject = 'Test is a test'
$message.Body = 'This message is being sent through EWS with PowerShell'

This post was a response to a query from one of my readers — thanks for the question, Nick. As a side note, the above code sample is based on a snippet from my guest post on the Hey Scripting Guy blog from a while back. For more details, you can check it out here.

0 comments… add one

Leave a Comment