Office 365 / Outlook.com OAuth example for retrieving e-mail

Microsoft and Google are stopping with support for imap with the standard/basic authentication. In exchange OAuth2 authentication is added. While the imap-protocol is enriched with OAuth headers, it is advised to start using REST-API's for retrieving e-mail from Office 365.

While the API isn't that hard to work with, the OAuth2-authentication is kinda tricky to get started with. One reason is that the documentation is not really clear. In enterprise-environments a 'resource'-variable is required, while for normal outlook 'scopes' is set. Second is that the errors are not clear in telling what is exactly going wrong.


First thing to do is registering your application in the Azure-portal

Go to portal.azure.com and go to 'Manage Azure Active Directory' => 'View'




Next, register a new application,
Azure register new app


For applications it's required to use the https-protocol, or use a development environment at http://localhost/



When the application is registered in the overview the client-settings are shown.



After the application is registered, API-permissions must be set for the application. Here it's specified to what specific services the application will get access to.



Last thing is to create a Client-secret under "Certificate & Secrets"




Now that the application is set-up and registered at the Azure/Office 365 side programming can start.

First thing is to request an access_token. This is done by redirecting the user to a Microsoft authentication-page:

<?php 
        $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
        
        $params = array();
        $params['client_id']      = '1234567890abcdef0987654321';
        $params['response_type']  = 'code';
        $params['redirect_uri']   = 'http://localhost/';
        $params['response_mode']  = 'query';
        $params['state']          = 'somecode';
        $params['scope']          = 'https://outlook.office.com/mail.read';

        header('Location: ' . $url . '?' . http_build_query($params));



After authentication succeeded - or failed - the user is redirected back to the redirect_uri. Note that the redirect_uri must correspond with the entered redirect-uri at registration of the application.

A return-url looks like: http://localhost/?code=K12345678-ab12-ab12-ab12-abcdefghijkl&state=somecode

With the received code an oauth2 access_token can be requested through the token-api:
<php
        $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
        
        $params = array();
        $params['grant_type']    = 'authorization_code';
        $params['client_id']     = '1234567890abcdef0987654321';
        $params['client_secret'] = 'FjsfdmnEWRYt28131==-';
        $params['code']          = $_GET['code'];
        $params['redirect_uri']  = 'http://localhost/';
        $params['scope']         = 'https://outlook.office.com/mail.read';

        // in an enterprise-environment the 'resource' parameter might work, while scopes don't
//        $params['resource']      = 'https://outlook.office.com/';
        
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-type: application/json'
        ));
        
        $r = curl_exec($ch);
        
        curl_close($ch);
        
        $json = json_decode($r);
        
        $json->access_token;



Now that your web-application is fully authenticated and an access_token is available, request to the Office 365 REST API can be made. An example for requesting e-mail from Outlook.com,

<php
        $url = 'https://outlook.office.com/api/v2.0/me/MailFolders/Inbox/messages';
        
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Accept: application/json',
            'Authorization: Bearer '.$access_token
        ));
        
        $r = curl_exec($ch);
        
        curl_close($ch);
        
        $json = json_decode( $r );

        var_export( $json );



More information about the API can be found at Microsoft @ https://docs.microsoft.com/en-us/previous-versions/office/office-365-api/api/version-2.0/use-outlook-rest-api


- Bent u opzoek naar een Php of Java programmeur voor uw website of applicatie? (freelance / detachering)
- Losse tickets, opdrachten, of gehele projecten in de planning?
- Systeembeheer van Linux of Windows Server ?

Dan kom ik graag met u in contact! Meer informatie over mij vindt u hier.
Sitemap | Op alle producten & diensten zijn de algemene voorwaarden van toepassing