X

How to get/read Outlook Office 365 mail using oauth PHP

In this tutorial i will show how to read outlook office 365 emails using oauth in PHP, Outlook.com is a web-based email and calendar etc services from Microsoft. One of the world’s first webmail services.

A running demo and code for download available below.

I will guide you step by step through pictures and code.

Step 1:- Go to https://apps.dev.microsoft.com/ and Click on “Add an app”

Step 2:- Input your application name and create.

Step 3:- You will get application id now create application secret, click Generate New Password button.

Step 4:- Copy that password and store it you will not see it again.

Step 5:- Now add Platform and select platform.

Select Web platform.

Step 6:- Add your application redirect url “https://phplift.net/demos/outlook-office365/redirect.php” (Your url would be different) you can add multiple redirect urls.

Click on save button that’s it your app is configured now coding time.

Coding:

config.php Contain Application id, sec etc.

<?php

    session_start();

    

    // define your api credentils and redirect url

    define("client_id", "YOUR-APPLICATION-ID");

    define("client_secret", "YOUR-APPLICATION-SECRET");

    define("redirect_uri", "YOUR-APPLICATION-REDIRECT-URI");

    

    

    // Static urls

    define("scopes", array("offline_access", "openid","https://outlook.office.com/mail.read"));

    define("accessUrl", "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=".client_id."&redirect_uri=".redirect_uri."&response_type=code&scope=".implode(" ", scopes));

    define("token_url", "https://login.microsoftonline.com/common/oauth2/v2.0/token");

    define("api_url", "https://outlook.office.com/api/v2.0");

?>

You have to change client_idclient_secret and redirect_uri with your application data.

index.php contain all functions view profile, all emails and view email.

<?php

include("config.php");



if(isset($_SESSION["access_token"])) {

    echo "<a href='index.php''>Home</a>";

    

    echo " || <a href='index.php?list_email=true'>List Email</a>";

    

    echo " || <a href='index.php?profile=true'>Profile</a>";

    

    echo " || <a href='logout.php'>Logout</a><br/><br/>";

    

    if(isset($_GET["profile"])) {

        view_profile();

    }

    else if(isset($_GET["list_email"])) {

        list_email();

    }

    else if(isset($_GET["view_email"])) {

        view_email();

    }

}

else{

    $accessUrl = accessUrl;

    echo "<a href='$accessUrl'>Login with Office 365</a>";

}



function view_profile() {

    $headers = array(

        "User-Agent: phplift.net/1.0",

        "Authorization: Bearer ".$_SESSION["access_token"],

        "Accept: application/json"

    );

    $outlookApiUrl = api_url."/Me";

    $response = runCurl($outlookApiUrl, null, $headers);

    $response = explode("\n", trim($response));

    $response = $response[count($response) - 1];

    $response = json_decode($response);

    

    echo "User ID: ".$response->Id."<br><br>";

    echo "User Email: ".$response->EmailAddress;

}



function list_email() {

    $headers = array(

        "User-Agent: phplift.net/1.0",

        "Authorization: Bearer ".$_SESSION["access_token"],

        "Accept: application/json",

        "X-AnchorMailbox: ". $_SESSION["user_email"]

    );

    $top = 10;

    $skip = isset($_GET["skip"]) ? intval($_GET["skip"]) : 0;

    $search = array (

        // Only return selected fields

        "\$select" => "Subject,ReceivedDateTime,Sender,From,ToRecipients,HasAttachments,BodyPreview",

        // Sort by ReceivedDateTime, newest first

        "\$orderby" => "ReceivedDateTime DESC",

        // Return at most n results

        "\$top" => $top, "\$skip" => $skip

    );

    $outlookApiUrl = api_url . "/Me/MailFolders/Inbox/Messages?" . http_build_query($search);

    $response = runCurl($outlookApiUrl, null, $headers);

    $response = explode("\n", trim($response));

    $response = $response[count($response) - 1];

    $response = json_decode($response, true);

    //echo "<pre>"; print_r($response); echo "</pre>";

    if(isset($response["value"]) && count($response["value"]) > 0) {

        echo "<style type='text/css'>td{border: 2px solid #cccccc;padding: 30px;text-align: center;vertical-align: top;}</style>";

        echo "<table style='width: 100%;'><tr><th>From</th><th>Subject</th><th>Preview</th></tr>";

        foreach ($response["value"] as $mail) {

            $BodyPreview = str_replace("\n", "<br/>", $mail["BodyPreview"]);

            echo "<tr>";

            echo "<td>".$mail["From"]["EmailAddress"]["Address"].

                "<br/><a target='_blank' href='?view_email=".$mail["Id"]."'>View Email</a>";

            if($mail["HasAttachments"] == 1) {

                echo "<br/><a target='_blank' href='?view_attachments=".$mail["Id"]."'>View Attachments</a>";

            }

            echo "</td><td>".$mail["Subject"]."</td>";

            echo "<td>".$BodyPreview."</td>";

            echo "</tr>";

        }

        echo "</table>";

    }

    else {

        echo "<div><h3><i>No email found</i></h3></div>";

    }

    $prevLink = "";

    if($skip > 0) {

        $prev = $skip - $top;

        $prevLink = "<a href='?list_email=true&skip=".$prev."'>Previous Page</a>";

    }

    if(isset($response["@odata.nextLink"])) {

        if($prevLink != "") {

            $prevLink .= " ||| ";

        }

        echo "<br/>".$prevLink."<a href='?list_email=true&skip=".($skip + $top)."'>Next Page</a>";

    }

    else {

        echo "<br/>" . $prevLink;

    }

}



function view_email() {

    $mailID = $_GET["view_email"];

    $headers = array(

        "User-Agent: phplift.net/1.0",

        "Authorization: Bearer ".$_SESSION["access_token"],

        "Accept: application/json",

        "X-AnchorMailbox: ".$_SESSION["user_email"]

    );

    $outlookApiUrl = api_url . "/me/Messages('$mailID')";

    $response = runCurl($outlookApiUrl, null, $headers);

    $response = explode("\n", trim($response));

    $response = $response[count($response) - 1];

    $response = json_decode($response, true);

    echo "From: ".$response['Sender']['EmailAddress']['Name']." (".$response['Sender']['EmailAddress']['Address'].")<br>";

    echo "To: ";

    foreach($response['ToRecipients'] as $to)

    {

        echo $to['EmailAddress']['Name']." (".$to['EmailAddress']['Name'].") ";

    }

    echo "<br>";

    $ReceivedDateTime = date("Y-m-d H:i:s",mktime($response['ReceivedDateTime']));

    echo "Received on: ".$ReceivedDateTime."<br>";

    echo "Subject: ".$response['Subject']."<br><br><hr />";

    

    echo $response['Body']['Content'];

}



?>

view_profile() Show authorized users profile and email address.

list_email() Show all emails in your inbox.

view_email() Show a particular email

redirect.php file contain code to extract access token from code and store access token and user email in session.

<?php

include("config.php");

if(isset($_GET["code"])){

    

    // Get access token

    $token_request_data = array (

        "grant_type" => "authorization_code",

        "code" => $_GET["code"],

        "redirect_uri" => redirect_uri,

        "scope" => implode(" ", scopes),

        "client_id" => client_id,

        "client_secret" => client_secret

    );

    $body = http_build_query($token_request_data);

    $response = runCurl(token_url, $body);

    $response = json_decode($response);

    $_SESSION["access_token"] = $response->access_token;

    

    // Get user email

    $headers = array(

        "User-Agent: phplift.net/1.0",

        "Authorization: Bearer ".$_SESSION["access_token"],

        "Accept: application/json"

    );

    $outlookApiUrl = api_url."/Me";

    $response = runCurl($outlookApiUrl, null, $headers);

    $response = explode("\n", trim($response));

    $response = $response[count($response) - 1];

    $response = json_decode($response);

    

    $_SESSION["user_email"] = $response->EmailAddress;

    

    header("Location: index.php");

}

 

?>

Code finished now you have to run index.php file it will show you a link to login with office 365.

I hope you liked this tutorial feel free to comment below if you face any issue I love to solve your issues.

Huzoor Bux: I am a PHP Developer

View Comments (5)

  • When i was run this script i got this error

    Uncaught Error: Call to undefined function runCurl()

    please help

  • When i was run this script i got this error

    Uncaught Error: Call to undefined function runCurl()

    But I made a Custom function

    function runCurl($token_url, $token_request_data){

    $curl = curl_init();

    curl_setopt_array($curl, array(

    CURLOPT_URL => $token_url,

    CURLOPT_RETURNTRANSFER => true,

    CURLOPT_SSL_VERIFYPEER => false, // "",

    CURLOPT_MAXREDIRS => 10,

    CURLOPT_TIMEOUT => 30,

    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,

    CURLOPT_POST => 1,

    // CURLOPT_CUSTOMREQUEST => "POST", // 1" instead.

    CURLOPT_POSTFIELDS => $token_request_data, // array(

    "application/x-www-form-urlencoded" //EmailAddress;

    I did not got the user_email

    I have no response from api URL

    Pls help