• Home
  • PHP
  • MySQL
  • Laravel
  • Demos
  • HTML
  • jQuery
  • Framework
  • Request Tutorial
PHP Lift
  • Home
  • Demos
  • Advertisement
PHP Lift
  • Home
  • PHP
  • MySQL
  • Laravel
  • Demos
  • HTML
  • jQuery
  • Framework
  • Request Tutorial
  • Follow
    • Facebook
    • Twitter
    • Google+
    • Pinterest
    • Youtube
    • Instagram
    • RSS
How to get/read Outlook Office 365 mail using oauth PHP
Home
oAuth

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

July 27th, 2025 Huzoor Bux API, oAuth, PHP 5 comments

Facebook Twitter Google+ LinkedIn Pinterest

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.

DEMO
DOWNLOAD CODE

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”

Outlook Office 365 mail using oauth PHP step 1

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_id, client_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.

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook

Related

  • Tags
  • microsoft
  • oauth
  • office 356
  • outlook
  • PHP
Facebook Twitter Google+ LinkedIn Pinterest
Next article Javascript let vs var
Previous article Validation of HTML5 documents

Huzoor Bux

I am a PHP Developer

Related Posts

Laboratory Management System (LIMS) in PHP MySQL – A Complete Guide MySQL
August 20th, 2025

Laboratory Management System (LIMS) in PHP MySQL – A Complete Guide

PHP Contact Form with Google reCAPTCHA V3 Example API
August 4th, 2025

PHP Contact Form with Google reCAPTCHA V3 Example

Drag and drop multiple file upload using jQuery, Ajax, and PHP JavaScript
August 4th, 2025

Drag and drop multiple file upload using jQuery, Ajax, and PHP

5 Comments

  1. Anuj
    April 20, 2021 at 12:03 pm Reply ↓

    When i was run this script i got this error

    Uncaught Error: Call to undefined function runCurl()

    please help

    1. tommie
      April 9, 2022 at 11:12 am Reply ↓

      I got the same error, did you manage to debug it?

  2. Indhu
    August 9, 2022 at 12:19 pm Reply ↓

    Please do post runCurl() funtion code.

  3. Priya
    August 9, 2022 at 12:22 pm Reply ↓

    Please do post runCurl() funtion code.

  4. Samay
    September 21, 2022 at 4:58 am Reply ↓

    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

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe
Get new posts by email:
Powered by follow.it
Advertisement
Like us
Recent Posts
  • Laboratory Management System (LIMS) in PHP MySQL – A Complete Guide
  • Cool New JavaScript Features
  • WhatsApp chatbot in Python using Dialogflow.com
  • Cool CSS3 features
  • PHP Contact Form with Google reCAPTCHA V3 Example
Categories
  • API
  • Bootstrap
  • Bot
  • CSS
  • CSS 3
  • Database
  • Designing
  • Framework
  • Guide
  • HTML
  • HTML 5
  • JavaScript
  • jQuery
  • Laravel
  • MySQL
  • Node.js
  • oAuth
  • Payment
  • PHP
  • Python
  • Social
  • Tips
  • Web 3.0
  • WordPress
Weekly Tags
  • PHP
  • javascript
  • How to
  • laravel
  • css
  • HTML to PDF
  • jQuery
  • api
  • Web Development
  • MYSQL
  • About
  • Privacy Policy
  • Back to top
© PHPLift.net. All rights reserved.
 

Loading Comments...