none
Save an email through EWS Managed API 2.2 via Windows PowerShell RRS feed

  • Question

  • 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

    Thursday, March 12, 2015 4:53 PM

All replies

  • >> 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

    Monday, March 16, 2015 12:02 AM
  • 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

    Tuesday, March 17, 2015 8:37 PM
  • 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

    Wednesday, March 18, 2015 12:28 AM
  • >> 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

    Hi,

    I had the error "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel." In my scenario I need to access the EWS through 127.0.0.1. So make the certificate trustable was not an option. Your code snippet solved my problem.

    Thank you

    Thursday, December 12, 2019 2:46 PM