Save an email through EWS Managed API 2.2 via Windows PowerShell

EWS API 2.2;  Exchange 2010 SP3

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2)

$service.Credentials = new-object Microsoft.Exchange.WebServices.Data.WebCredentials("ktu","****","adaxes")

$service.AutodiscoverUrl("ktu@carexel.com")

$message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service

$message.Subject = "This Message has been Created by EWS"

$message.From = "ktutesting@carexel.com"

$message.ToRecipients.Add('EwsTestingTo@LetsExchange.com')

$message.Body = "This is Test Message By Sunil Chauhan From EWS Client"

$message.Save()

===============================================

Try to save an email by using the above cmdlets, get error:

SendAndSaveCopy : Exception calling "SendAndSaveCopy" with "0" argument(s): "The request failed. The underlying connect
ion was closed: An unexpected error occurred on a send."
At line:1 char:22
+ $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

I found a thread below, however it doesn't work in our scenario because we do use valid SSL certificate.

https://social.technet.microsoft.com/Forums/office/en-US/ad493b72-6465-450b-bd49-8f15675d7f53/dotnetmethodexception-error-on-mailsendandsavecopy?forum=exchangesvrdevelopment

Thanks,

Kevin

March 12th, 2015 12:54pm

>> found a thread below, however it doesn't work in our scenario because we do use valid SSL certificate

You need some code to deal with that then I would suggest you try this (Make sure you shutdown any existing powershell session you have open before you run it). This will ignore any self signed SSL errors

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

  
## 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
$service.Credentials = new-object Microsoft.Exchange.WebServices.Data.WebCredentials("ktu","****","adaxes")

$service.AutodiscoverUrl("ktu@carexel.com",{$true})  

$message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service

$message.Subject = "This Message has been Created by EWS"

$message.From = "ktutesting@carexel.com"

$message.ToRecipients.Add('EwsTestingTo@LetsExchange.com')

$message.Body = "This is Test Message By Sunil Chauhan From EWS Client"

$message.Save()
Cheers
Glen

Free Windows Admin Tool Kit Click here and download it now
March 15th, 2015 8:03pm

Hi Glen,

Actually, the method you provided is the one I already saw, tried and pointed it out in my question.

Anyway, I tried it again and it didn't work...

Thanks,

Kevin

March 17th, 2015 4:38pm

You can get more information on the error using $error | fl

I've not found an instance where that method hasn't work, I would check if you have used

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

If you have this will break the managed API this setting will persist in a Powershell session hence why I said you need to shutdown any PS session before you try running the script. You might want to try adding this as the first line which should counter that

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null

Cheers
Glen

Free Windows Admin Tool Kit Click here and download it now
March 17th, 2015 8:29pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics