How to Use The Microsoft Exchange Email API Via EWS

Learn how to use the Microsoft Exchange Email API with EWS, and discover how Nylas simplifies your next email integration.

How to Use The Microsoft Exchange Email API Via EWS

Microsoft’s Exchange Web Services (EWS) provides an Exchange email API that provides access to all of the data and functionality in Exchange mailboxes; it enables developers to parse email data, create email drafts, send emails, manage attachments, and organize an email inbox with folders. EWS offers a direct SOAP implementation and C# client library that provides full access to user accounts in Exchange Online, Exchange Online as part of Office 365, and Exchange server inboxes. 

If you’re looking to integrate Exchange inboxes directly into your app, this post will detail the major aspects of the Exchange Email API and explain what it takes to integrate Exchange email inboxes. It will also demonstrate how the Nylas Communications Platform abstracts away much of the complexity of building a direct integration with the Exchange email API to enable you to build your calendar integration much more quickly and efficiently.

Connect Exchange Accounts to Your App.

Before you can access an Exchange inbox via the EWS API, you need to authenticate the account with the appropriate permissions. Take a look at our guide on How to Use the EWS API to Authenticate Accounts Into Your App to learn more. Are you confused by all the related products in the Microsoft Exchange ecosystem? Our Microsoft Exchange definitions guide will set you straight.

Once you’ve decided how you’re going to authenticate user accounts, it’s time to start digging in to EWS functionality. Let’s get started!

Connect Your First Exchange Account in Minutes Using Nylas

Get a quick demonstration on integrating Microsoft Exchange with your application.

How to Parse Email Messages

One of the most basic functions of any email integration is the ability to parse the contents of an email message. In Exchange, messages are classified as strongly typed items, which includes other Exchange components like calendar events, contacts, and tasks. Messages contain a number of useful properties, including the subject, body, attachments, sender and recipient information, and more. The GetItem function enables you to retrieve an email message from a user’s inbox by providing the ItemId for the message and the ItemShape that indicates which properties to return.

Here’s an example of a get request for an Exchange email message with the default ItemShape:

<soap:Envelope>
  <soap:Body>
    <GetItem>
      <ItemShape>
        <BaseShape>Default</BaseShape>
        <IncludeMimeContent>true</IncludeMimeContent>
      </ItemShape>
      <ItemIds>
        <ItemId Id="JFJFNQWICJKW" ChangeKey="FSGHSDYU" />
      </ItemIds>
    </GetItem>
  </soap:Body>
</soap:Envelope>

This request returns a Message element that contains all of the requested data for the email.

Create and Send an Email

No email integration is complete without the ability to create and send email messages; this is where the CreateItem operation comes in. When using this operation for an email, it requires you to set a MessageDisposition attribute from one of the following options: 

  • SaveOnly – The message is saved in the folder that’s indicated with the SavedItemFolderId attribute. This message can then be sent at a later time (more on this later). 
  • SendOnly – The message will be sent without saving it to the sent folder.
  • SendAndSaveCopy – The message will be sent and saved to the folder specified in the SavedItemFolderId attribute.

Here is an example of an EWS XML request to send an email and save it to the user’s draft folder:

<soap:Envelope >
  <soap:Body>
    <CreateItem>
      <SavedItemFolderId>
        <DistinguishedFolderId Id="drafts" />
      </SavedItemFolderId>
      <Items>
        <Message>
          <ItemClass>IPM.Note</ItemClass>
          <Subject>This is the Email Subject Line</Subject>
          <Body BodyType="Text">This is the email body</Body>
          <ToRecipients>
            <Mailbox>
              <EmailAddress>email@example.com</EmailAddress>
            </Mailbox>
          </ToRecipients>
          <IsRead>false</IsRead>
        </Message>
      </Items>
    </CreateItem>
  </soap:Body>
</soap:Envelope>

Once done, the server responds to the request with a CreateItemResponse message that indicates if the execution was successful, if so, the response includes the ItemId for the newly created message. If the request fails, the server will provide ResponseCode and MessageText attributes that describe the error. 

Reply to and Forward Emails

The process to reply to and forward emails is very similar to the standard process for creating an email message. To do so, include either a ReplyToItem, ReplyAllToItem, or ForwardItem child attribute when invoking the CreateItem operation that indicates the ReferenceItemId for the original email message. 

Send an Existing Email Draft 

There are two steps to sending an email with the EWS email API:

  1. Retrieve the message you want to send with the GetItem operation, specifying the ItemId for the message you want.
  2. Use the SendItem operation to send the email, specifying whether or not the message should be saved to a folder upon completion. 

Here is an example of an EWS email API XML request to send an existing email draft: 

<soap:Envelope>
  <soap:Body>
    <SendItem SaveItemToFolder="true">
      <ItemIds>
        <ItemId Id="FJGSDFGSD=" ChangeKey="SDFGSDH+T" />
      </ItemIds>
    </SendItem>
  </soap:Body>
</soap:Envelope>

If this is successful, the Exchange server will respond with the message’s id, subject, and recipients.

Move and Copy Emails 

The MoveItem and CopyItem functions allow you to move or copy email messages into a new folder. You need to include a the email’s ID and a DistinguishedFolderId as part of the request to indicate the destination folder. For example, here is a request to move a message to the user’s drafts folder:

<soap:Envelope>
  <soap:Body>
    <MoveItem>
      <ToFolderId>
        <DistinguishedFolderId Id="drafts"/>
      </ToFolderId>
      <ItemIds>
        <ItemId Id="jvb8qej544bdfmbj" ChangeKey="dfgadfh85je"/>
      </ItemIds>
    </MoveItem>
  </soap:Body>
</soap:Envelope>

There’s one very important thing to keep in mind when you move or copy an email message into a different folder: a new item is created in the new folder with a unique ItemId and the original message is deleted. If you’re moving or copying an email message between two folders in the same mailbox, the new item is returned in the response, giving you access to the new ItemId. However, If you’re moving or copying an email message between two mailboxes or between a mailbox and a public folder, the new item is not returned in the response. If you need to access the moved message in the latter scenario, you can create and set a custom extended property and then search for this property in the new folder with the FindItem operation.

Delete Emails

There are two ways to delete an email from a user’s inbox. The first is the MoveItem operation, which can be used to move the email into the user’s trash folder. This is the least permanent method and is effectively the same as the user moving the email to the trash themselves.

Alternatively, the DeleteItem operation moves the email into the user’s recoverable items folder. This is effectively the same as the user permanently deleting the email, making it unavailable via normal user interaction. However, this doesn’t necessarily mean the email is permanently deleted. Instead, it follows the user’s deleted item retention policies which may result in it being permanently deleted after a specific amount of time.

Manage File Attachments

EWS APIs use two primary forms of attachments:

  • Item Attachments – Strongly-typed EWS Items that include email messages, calendars, events, tasks, contacts and more that are associated with the requested element.
  • File Attachments – Base-64 encoded content that represents any type of file including documents, images, videos, archives, and more.

The focus of this section will be on how to work with file attachments.

Parse Email Attachments

Email attachments in EWS are represented as FileAttachment elements that include the name of the file, content type, ID, file size, and more. When you use the GetItem operation to retrieve an email message, it will include an Attachments element that lists the id for any file attachments that are associated with the email message:

<Message>
  <Attachments>
    <FileAttachment>
      <AttachmentId Id="AAAtAEFk=" RootItemId="AAAtAEFkb=" RootItemChangeKey="CQAAABYA"/>
    </FileAttachment>
  </Attachments>
</Message>

You can then include this ID in a GetAttachment request that will create a response that includes information about the file attachment and it’s contents. Here’s an abbreviated example of a response to the GetAttachment operation:

<Envelope>
  <Body>
    <GetAttachmentResponse">
      <ResponseMessages>
        <GetAttachmentResponseMessage ResponseClass="Success">
          <ResponseCode>NoError</ResponseCode>
          <Attachments>
            <FileAttachment>
              <AttachmentId Id="SGHSGHhHHGkhh"/>
              <Name>My_Document.pdf</Name>
              <Content>ASDFJASDGF=</Content>
            </FileAttachment>
          </Attachments>
        </GetAttachmentResponseMessage>
      </ResponseMessages>
    </GetAttachmentResponse>
  </Body>
</Envelope>

If you need to access the file contents, you will need to decode the text found in the Content element.

Send an Email With Attachments

To add an attachment to a new email draft, create a FileAttachment element when invoking the CreateItem operation to create a new email message.  You can specify the name, whether it’s inline in the email body, and if an image is a contact profile image. It also must include the raw base-64 encoded content. 

If you want to add an attachment to an existing email message, you can do so with the CreateAttachment operation that uses the same FileAttachment element as before to attach the file to the message that’s specified in the ParentItemId element.  

EWS Inbox Notifications

EWS provides a notification system that lets your app receive information whenever the content of a user’s inbox changes, and this is available for all Item and Folder elements, including email messages. The EWS notification system enables you to track things like the creation, deletion, or update of an email message or inbox folder as specified in the EventType element. EWS offers two recommended notification types:

  • Streaming notifications – The Exchange server establishes an active connection to your app for up to 30 minutes, during which it sends your app all of the updates you asked for. Microsoft recommends this method whenever possible.
  • Pull notifications – The Exchange server provides your app with a Watermark element that indicates a specific point in time. Your app uses the Watermark token to regularly query the Exchange server to get a list of notifications about changes that have happened to an email inbox since the time of the watermark. This is best for client devices that have unreliable data connections.

Nylas Makes Email Integrations Simple

Chances are, that you’re not an expert on email API integrations, and connecting your app to Exchange accounts can seem like a daunting task. Nylas specializes in email and calendar connectivity and offers an industry-leading Email API that instantly integrates 100% of email providers into your app. Without Nylas, it could take you up to 16,530 hours just to build a complete integration with Exchange; that same task with Nylas would take a single engineer as little as 18 days. Let’s take a look at a few of the features that make Nylas the obvious choice for your email integration.

Auto-Detect Email Providers With Hosted Auth

Authentication protocols are complex, Nylas makes them easy with Hosted Auth, which auto-detects 100% of email providers and prompts users to sign in and accept the permissions your app needs. Third-party access credentials are stored safely on our SOC 2 Certified infrastructure, and Nylas provides an access token your app can use for complete Exchange email data and functionality. 

Illustration of the Nylas Hosted Auth service that integrates with 100% of email, calendar, and contacts providers, including Google

With Nylas, integrating with additional email providers beyond EWS requires no additional work, so you’ll have a seamless development experience when you’re ready to expand your user base to other providers like Outlook, Office 365, Gmail, and more.

Integrate a Modern REST API With JSON Data

SOAP is an older protocol that requires the use of highly-structured XML for all requests; this comes with increased complexity and bandwidth usage. The Nylas Email API applies a modern RESTful approach to email data and functionality and allows you to work in a simple JSON format. For example, the Messages endpoint lets you access all user emails that have been synced to Nylas. Here’s what one of those messages might look like:

    {
        "object": "message",
        "subject": "Re: Spacefaring Ornithopters",
        "body": "These look great! We should setup a time to discuss.",
        "unread": true,
        "thread_id": "cvsppk492j",
        "from": [
            {
                "name":"Katherine Johnson",
                "email":"kat@spacetech.com"
            }
        ],
        "to": [
            {
                "name": "Leonardo Da Vinci",
                "email": "leo@ornitech.com"
            }
        ],
        "folder": {
            "display_name": "Inbox",
            "id": "7hcggf94js",
            "name": "inbox"
        }
    }

Threads as First Class Objects

In the last example, you might have noticed the thread_id attribute. Individual email messages don’t exist in a vacuum, they’re a part of a broader conversation that can sometimes involve numerous messages with multiple participants. EWS doesn’t provide any supporting operations to help you implement email threading, leaving you to build it from scratch yourself. Nylas, on the other hand, treats threads as first class objects, which makes it much easier to work with email conversations that involve multiple messages.  Here’s an example of a response from the Nylas Threads endpoint:

{
    "object": "thread",
    "subject": "Spacefaring Ornithopters",
    "snippet": "Check out our newest line...",
    "participants":[
        {
            "name": "Leonardo Da Vinci",
            "email": "leo@ornitech.com"
        },
        {
            "name":"Katherine Johnson",
            "email":"kat@spacetech.com"
        }
    ],
    "message_ids":[
      "asfhdg8542j10toy",
      "knknowkfdhn498da"
    ]
}

Built In Support for Open, Click, and Reply Tracking

EWS only offers basic access to email data and functionality. Nylas has many features that enable you to take your integration further, like out of the box support for open, click, and reply tracking that gives you better insight into how users are engaging with emails sent via your app.

More Reliable Inbox Notifications

EWS has fairly limited capabilities for notifying your app about updates to a user’s inbox, and their recommended solution is a streaming notification service that requires you to refresh the connection every 30 minutes. This can become cumbersome as the number of users you have connected to your app grows. Nylas provides Webhooks that only need to be configured once, and will continue to send notifications to your app for all connected accounts, as long as you need. Our webhooks let you monitor for new emails that are sent or received and all open, click, and reply tracking interactions.

File Attachments Made Easy

The EWS API has a fairly complex method for handling email attachments that requires you to deal with base-64 encoded text, regardless of the file types you’re working with. The Nylas Files endpoint makes it extremely easy to download and upload email attachments. If you want to attach a file to an email, the first step is to upload the file to the Nylas Communications Platform:

curl -X POST 'https://api.nylas.com/files/' \
-H 'Authorization: Bearer ACCESS_TOKEN' \
--form 'file=@/2021_Ornithopter_Models.pdf'

Once the file is uploaded, Nylas provides a JSON representation of it that contains the name, content type, id, and more:

{
    "object": "file",
    "filename": "2021_Ornithopter_Models.pdf",
    "content_type": "application/pdf",
    "id": "9etjh6talp1m",
    "size": 72379
}

Then, when you want to attach the file to an email that’s being sent, add the ID for the file to the file_ids attribute of the email message. 

curl -X POST 'https://api.nylas.com/send' \
-H 'Authorization: Bearer ACCESS_TOKEN' \
-d '{
    "from": [{
        "name": "Leonardo Da Vinci",
        "email": "leo@ornitech.com"
    }],
    "to": [{
        "name":"Katherine Johnson",
        "email":"kat@spacetech.com"
    }],
    "subject": "Spacefaring Ornithopters",
    "body": "Check out our newest lines of ornithopters to suit any needs.",
    "file_ids": ["9etjh6talp1m"]
}'

That’s it! Nylas handles everything else for you, including syncing the file with EWS.

Take Your Email Integration Further With Nylas

Why Stop with Exchange? Nylas supports 100% of email, calendar, and contacts providers out of the box, enabling your users to keep using their calendar provider of choice. This post has only covered a fraction of the benefits the Nylas Communications Platform provides, and we haven’t even touched on the benefits we provide if you’re seeking to integrate EWS calendar functionality too. 

Connect Your First Exchange Account in Minutes Using Nylas

Sign up for a Nylas developer account and try integrating Microsoft Exchange with your application.

What’s Next?

Don’t miss the action and watch our livestream Coding with Nylas:

You May Also Like

How to create and read Webhooks with PHP, Koyeb and Bruno
How to create a scheduler with Python and Taipy
How to create and read Google Webhooks using Kotlin

Subscribe for our updates

Please enter your email address and receive the latest updates.