Using Asynchronous Operations in EWSClient

Unlike the synchronous methods, the asynchronous methods are non-blocking and allow to perform multiple requests simultaneously. Asynchronous methods are named with the Async postfix.

NOTE: Async methods are available in versions targeting .NET Core, .NET Framework 4.5, and later.

Implementing IAsyncTokenProvider to get OAuth Tokens Asynchronously

The following code sample defines a SomeAsyncTokenProvider class, which implements the IAsyncTokenProvider interface. The class implements GetAccessTokenAsync asynchronous method that returns a Task of type OAuthToken. This method fetches a valid OAuthToken asynchronously.

private class SomeAsyncTokenProvider : IAsyncTokenProvider
{
    public SomeAsyncTokenProvider( /*some parameters*/)
    {
        ...
    }

    public async Task<OAuthToken> GetAccessTokenAsync(bool ignoreExistingToken = false,
        CancellationToken cancellationToken = default)
    {
        //Some asynchronous code to get a valid OAuthToken
        ...
    }

    public void Dispose()
    {
        ...
    }
}

Creating the IAsyncEwsClientInstance

The next code example obtains an Exchange Web Services (EWS) client asynchronously using OAuth authentication. The code performs the following steps:

  1. Creates a new CancellationToken object that can be used to cancel asynchronous operations.
  2. Instantiates SomeAsyncTokenProvider class that implements the IAsyncTokenProvider interface. This class is used as a parameter for constructing a new OAuthNetworkCredential object.
  3. Sets the mailbox URI to the Exchange Web Services endpoint.
  4. Calls the GetEwsClientAsync method of the EWSClient class with the mailboxUri and OAuthNetworkCredential object as parameters. This method returns a Task object, so it awaits the result before continuing. The cancellationToken object is passed as an optional parameter to the GetEwsClientAsync method.
//The cancellationToken can be used
var cancellationToken = new CancellationToken();

//Create IAsyncEwsClientInstance
IAsyncTokenProvider tokenProvider = new SomeAsyncTokenProvider(/*some parameters*/);
const string mailboxUri = "https://outlook.office365.com/ews/exchange.asmx";
var ewsClient = await EWSClient.GetEwsClientAsync(mailboxUri, new OAuthNetworkCredential(tokenProvider),
    cancellationToken: cancellationToken);

Sending a Message

The code example below is attempting to send an email message asynchronously. The code performs the following steps:

  1. Creates a new MailMessage object with the message parameters.
  2. Calls the SendAsync method of the EWSClient object, passing the MailMessage as a parameter. Method is awaited since it returns a Task object. The cancellationToken object is passed as an optional parameter to the SendAsync method.
MailMessage message = new MailMessage("from@aspose.com", "to@aspose.com", "Some subject", "Some body");
await ewsClient.SendAsync(message, cancellationToken: cancellationToken);

Fetching a Message with Attachments

To fetch an email message asynchronously, use the following code example with the steps described below:

  1. Call the FetchItemAsync method of an EWSclient. The method takes two parameters:

    • messageUri is a string representing the URI of the message to fetch
    • cancellationToken is an optional parameter that can be used to cancel the asynchronous operation. The method returns a Task object that resolves to a MapiMessage object when the asynchronous operation is complete. The “await” keyword is used to wait for the Task object to complete before proceeding.
  2. Assign to the fetched variable the result of the completed Task, which is a MapiMessage object containing the fetched message data.

       var fetched = await ewsClient.FetchItemAsync(messageUri, cancellationToken: cancellationToken);
    

Appending Messages

The code example below is attempting to append email messages asynchronously. The code performs the following steps:

  1. Calls the AppendMessagesAsync method of an EWSclient object. The method takes an EwsAppendMessage object that contains paremeters: the messages to append, the target folder URI, and the cancellation token.

  2. Creates the EwsAppendMessage object using the Create method and configures it with the following method calls:

    • AddMessage adds a message to the append operation.
    • SetFolder sets the target folder URI for the append operation.
    • SetCancellationToken sets the cancellation token that can be used to cancel the asynchronous operation.
  3. The AppendMessagesAsync method returns a Task object that resolves to an IEnumerable object when the asynchronous operation is complete. The “await” keyword is used to wait for the Task object to complete before proceeding.

  4. The uris variable is assigned the result of the completed Task, which is an IEnumerable object containing the URIs of the appended messages.

IEnumerable<string> uris = await ewsClient.AppendMessagesAsync(
    EwsAppendMessage.Create()
        .AddMessage(message)
        .AddMessage(fetched)
        .SetFolder(folderUri)
        .SetCancellationToken(cancellationToken));

Copying Items

The code sample below shows how to copy items and performs the following steps:

  1. Calls the CopyItemAsync method of an EWSClient object. The method takes three parameters:

    • messageUri is a string representing the URI of the message to copy
    • destinationFolderUri is a string representing the URI of the destination folder
    • cancellationToken is an optional parameter that can be used to cancel the asynchronous operation.

    The method returns a Task object that resolves to a string when the asynchronous operation is complete. The “await” keyword is used to wait for the Task object to complete before proceeding.

  2. newItemUri variable is assigned the result of the completed Task, which is a string containing the URI of the newly created copy of the message.

string newItemUri = await ewsClient.CopyItemAsync(messageUri, destinationFolderUri, cancellationToken);

Deleting Items

The following code is attempting to delete an email message asynchronously.

It calls the DeleteItemAsync method of an EWSClient object. The method takes three parameters:

  • newItemUri is a string representing the URI of the item to delete
  • DeletionOptions.DeletePermanently specifies that the item should be deleted permanently
  • cancellationToken is an optional parameter that can be used to cancel the asynchronous operation.

The method returns a Task object that completes when the asynchronous operation is complete. The “await” keyword is used to wait for the Task object to complete before proceeding.

await ewsClient.DeleteItemAsync(newItemUri, DeletionOptions.DeletePermanently, cancellationToken);

Deleting Folders

The following code is attempting to delete a folder asynchronously.

It calls the DeleteFolderAsync method of an EWSClient object. The method takes three parameters:

  • folderUri is a string representing the URI of the folder to delete
  • deletePermanently specifies whether to delete the folder permanently or move it to the “Deleted Items” folder
  • cancellationToken is an optional parameter that can be used to cancel the asynchronous operation.

The method returns a Task object that completes when the asynchronous operation is complete. The “await” keyword is used to wait for the Task object to complete before proceeding.

const bool deletePermanently = true;
await ewsClient.DeleteFolderAsync(folderUri, deletePermanently, cancellationToken);

Updating Items

The code example below is attempting to update an item asynchronously. It performs the following steps:

  1. Creates an EwsUpdateItem object using the Create method, passing in an item object. The EwsUpdateItem represents an update operation parameters. The SetCancellationToken method is called on the EwsUpdateItem object, passing in the cancellationToken parameter, which is an optional parameter that can be used to cancel the asynchronous operation.
  2. Passes the EwsUpdateItem object as a parameter to the UpdateItemAsync method of an EWSClient.
  3. The UpdateItemAsync method returns a Task object that completes when the asynchronous operation is complete. The “await” keyword is used to wait for the Task object to complete before proceeding.
await ewsClient.UpdateItemAsync(
    EwsUpdateItem.Create(mapiNote)
        .SetCancellationToken(cancellationToken));