• PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
PHP Lift
  • Home
  • Demos
  • PHP Jobs
  • Advertisement
PHP Lift
  • PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
  • Follow
    • Facebook
    • Twitter
    • Google+
    • Youtube
    • 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

January 16th, 2019 Huzoor Bux API, oAuth, PHP 0 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 Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Related

  • Tags
  • microsoft
  • oauth
  • office 356
  • outlook
  • PHP
Facebook Twitter Google+ LinkedIn Pinterest
Next article Stripe Payment Gateway Charge Credit Card with PHP
Previous article How to Download YouTube Video with PHP

Huzoor Bux

I am a PHP Developer

Related Posts

Stripe Payment Gateway Charge Credit Card with PHP API
February 15th, 2021

Stripe Payment Gateway Charge Credit Card with PHP

6 Reasons Laravel is the Top PHP Framework in the Web Development Industry Framework
February 1st, 2021

6 Reasons Laravel is the Top PHP Framework in the Web Development Industry

12 Reasons to Choose PHP for Developing Website Guide
November 17th, 2020

12 Reasons to Choose PHP for Developing Website

Leave a Reply Cancel reply

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

Advertisement
Recent Posts
  • Stripe Payment Gateway Charge Credit Card with PHP
  • How to building responsive WordPress theme using Bootstrap
  • 6 Reasons Laravel is the Top PHP Framework in the Web Development Industry
  • 9 Best Programming languages you should learn in 2021
  • 12 Reasons to Choose PHP for Developing Website
Categories
  • API
  • Bootstrap
  • CSS
  • CSS 3
  • Designing
  • Framework
  • Guide
  • HTML
  • HTML 5
  • JavaScript
  • jQuery
  • MySQL
  • Node.js
  • oAuth
  • Payment
  • PHP
  • Python
  • Social
  • Tips
  • WordPress
Weekly Tags
  • PHP
  • api
  • How to
  • PHP Basics
  • Programming Habits
  • HTML5
  • PHP framework
  • Download
  • laravel
  • css
  • About
  • Privacy Policy
  • Back to top
© PHPLift 2020. All rights reserved.