The Office 365 REST APIs (Mail, Calendar, Contacts, and Files) provide an easy way to integrate Office 365 features into your app. But what if your app is a mail app? With a little creativity, it’s not much different than any other app. Let’s take a look at how you can use the Files API to access OneDrive from within a mail app.
To be able to handle the redirect back from the OAuth authorization endpoint, most of the major processing happens in a Web API hosted on the same server as the mail app. The mail app presents the OAuth sign-in and consent UI, but the Web API handles the redirect back from the OAuth endpoint and completes the flow. The Web API then uses the OAuth access token to access OneDrive via the Files API.
Backstory: If you attended the mail app deep dive at SharePoint Conference 2014 (or watched the video), you may remember Andrew Salamatov showing a mail app that saved an attachment from an email message to SharePoint. Andrew asked me to take his app and polish it to publish as a sample. His sample was the starting point for this one. The end result of my tinkering is now on GitHub.
What’s it do?
The updated sample mail app activates in read forms for messages that have attachments. The user can authorize the app to access their OneDrive for Business, then click a button to save all file attachments to their OneDrive. The sample consists of two parts:
- The mail app (Home.html, Home.js) – This part shows up in Outlook and Outlook Web App. It provides the UI for the app, initiates the OAuth2 consent follow to Azure Active Directory, and sends the attachment IDs to the WebAPI component of the sample.
- The Web API (OAuthController.cs, GetAttachmentController.cs) – This part manages the OAuth2 response and caches the refresh token, uses Exchange Web Services to download attachment data, and uses the Files API to upload attachments to OneDrive for Business.
Things to note
- The Web API component uses an in-memory cache to store user’s refresh tokens for accessing OneDrive. This isn’t a great approach for a real app, where you want that data to survive app restarts and be better protected. For a real app, storing these tokens in a secure database is recommended.
- Because you have to open a new browser window to access the Azure AD logon site for OAuth, the UI for the “Authorize access” step is a little rough. Luckily this only has to happen once (until you restart the app!) since the refresh token will be cached.