Part 1. Getting Mailbox Data from Office API — Building Outlook Add-in with React

How to use Office Javascript API and get mailbox data in Outlook add-in with React

May Chen
NEXL Engineering
2 min readJul 24, 2021

--

More posts on buiding Outlook add-in with React:

Our product is a CRM so our Outlook add-in is built for our users to have a better understanding of the people they are communicating with while checking the emails.

NEXL 360 add-in

So our add-in needs to know which contacts are in the email a user is checking and Office API helps us to achieve that. In this post, we will go through how to get the email data through Office API.

If you don’t have your add-in up and running yet, check out this post on how to set up your add-in.

Setting it up

To use Office Javascript API, first thing is to add the script in our project.

So in index.html(under /public if you set up your app with create-react-app), we add this inside the <head>:

<script type="text/javascript" src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js"></script>

And if you are using Typescript (you are if you followed my last post), install the types so it doesn’t complain:

yarn add -D @types/office-js

Getting the data

Getting the data from Office API is as simple as this:

const item = Office.context.mailbox.item;

(Checkout what data you have access to in this documentation)

But one thing is this will only work after office.js is loaded so we only want to load our app after Office is ready.

Another thing is to make it simpler to write our business logic and not have every component access Office directly, we want to create our own context and have only the data we need from Office.

So, we have a <OfficeContext /> component which manages the state (whether office is initialised or not) and the data, it looks like this:

And in App.tsx, we do:

<OfficeContextProvider>
<OfficeContextConsumer>
({ isInitialized }) =>
isInitialized ? (
<Router>
{…}
</Router>
) : (
<LoadingOffice />
)}
</OfficeContextConsumer>
</OfficeContextProvider>

The isInitialized flag helps us to know if Office is ready or not to prevent loading the app without any data from Office.

Now in any component inside <OfficeContextProvider />, we can access the data like this:

const { state } = useOfficeContext();
const from = state?.mailbox?.item?.from;

--

--

May Chen
NEXL Engineering

A developer who occasionally has existential crisis and thinks if we are heading to the wrong direction, technology is just getting us there sooner.