Thursday, November 24, 2016

Send email using Php & Outlook / Office 365 using Oauth connection

To get oauth access token & other information used in this code snippet visit:
http://pritomkumar.blogspot.com/2016/11/write-php-app-to-get-outlook-office-365.html

Code snippet to send email using php via Office 365 account & oauth


<?php
session_start();
init();

if(isset($_POST["send"])) {
    $attachments = array();
    for($i = 0; $i < 6; $i++) {
        if(strlen(trim($_FILES["files"]["name"][$i])) > 0) {
            $content = base64_encode(file_get_contents($_FILES["files"]["tmp_name"][$i]));
            $attachment = array(
                "@odata.type" => "#Microsoft.OutlookServices.FileAttachment",
                "Name" => $_FILES["files"]["name"][$i],
                "ContentBytes" => $content
            );
            array_push($attachments, $attachment);
        }
    }

    $to = array();
    $toFromForm = explode(";", $_POST["to"]);
    foreach ($toFromForm as $eachTo) {
        if(strlen(trim($eachTo)) > 0) {
            $thisTo = array(
                "EmailAddress" => array(
                    "Address" => trim($eachTo)
                )
            );
            array_push($to, $thisTo);
        }
    }
    if (count($to) == 0) {
        die("Need email address to send email");
    }

    $request = array(
        "Message" => array(
            "Subject" =>$_POST["subject"],
            "ToRecipients" => $to,
            "Attachments" => $attachments,
            "Body" => array(
                "ContentType" => "HTML",
                "Content" => utf8_encode($_POST["message"])
            )
        )
    );

    $request = json_encode($request);
    $headers = array(
        "User-Agent: php-tutorial/1.0",
        "Authorization: Bearer ".$_SESSION["access_token"],
        "Accept: application/json",
        "Content-Type: application/json",
        "Content-Length: ". strlen($request)
    );

    $response = runCurl($_SESSION["api_url"], $request, $headers);
    echo "<pre>"; print_r($response); echo "</pre>";
    /* if $response["code"] == 202 then mail sent successfully */
}
else {
?>
<form method="post" enctype="multipart/form-data" accept-charset="ISO-8859-1">
<table style="width: 1000px;">
    <tr>
        <td style="width: 150px;">To</td>
        <td style="width: 850px;"><input type="text" name="to" required value="" style="width: 100%;"/></td>
    </tr>
    <tr>
        <td>Subject</td>
        <td><input type="text" name="subject" required value="Some sample subject on <?php echo date("d/m/Y H:i:s"); ?>" style="width: 100%;"/></td>
    </tr>
    <tr>
        <td>Files</td>
        <td>
            <input type="file" name="files[]"/>
            <input type="file" name="files[]"/>
            <input type="file" name="files[]"/>
            <input type="file" name="files[]"/>
            <input type="file" name="files[]"/>
            <input type="file" name="files[]"/>
        </td>
    </tr>
    <tr>
        <td style="vertical-align: top;">Message</td>
        <td><textarea name="message" required style="width: 100%; height: 600px;"></textarea></td>
    </tr>
    <tr>
        <td></td>
        <td><input type="submit" name="send" value="Send"/></td>
    </tr>
</table>
</form>
<?php
}

function init() {
    $_SESSION["scopes"] = array("offline_access", "openid", "https://outlook.office.com/mail.send");

    $_SESSION["api_url"] = "https://outlook.office.com/api/v2.0/me/sendmail";

    $_SESSION["access_token"] = "eyJ0eXAiOiJKV1QidfsdfsdfsdfSUzI1NiIsIng1dCI6IlJyUXF1OXJ5ZEJWUldtY29jdVhVYjIwSEdSTSIsImtpZCI6IlJyUXF1OXJ5ZEJWUldtY29jdVhVYjIwSEdSTSJ9.eyJhdWQiOiJodHRwczovL291dGxvb2sub2ZmaWNlLmNvbSIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzdkOTAzZjM5LTkxZGYtNGVmMS04ZDY0LTcxNDMwOTlhMTVmMC8iLCJpYXQiOjE0Nzk5NjE2NjAsIm5iZiI6MTQ3OTk2MTY2MCwiZXhwIjoxNDc5OTY1NTYwLCJhY3IiOiIxIiwiYW1yIjpbInB3ZCJdLCJhcHBpZCI6ImRhOGE1NGQ4LTg2YjUtNDE5Ni05ODFlLWUzMWVmYTNmM2Q1OSIsImFwcGlkYWNyIjoiMSIsImZhbWlseV9uYW1lIjoiQmlsbCIsImdpdmVuX25hbWUiOiJBdXRvIiwiaXBhZGRyIjoiMTAzLjQuMTQ2LjE4NiIsIm5hbWUiOiJBdXRvIEJpbGwiLCJvaWQiOiI5NGM1NTZlMy1jYmM1LTQxMTItYWJhZi0yMmUxZDVkNWU2ZjQiLCJwbGF0ZiI6IjMiLCJwdWlkIjoiMTAwMzAwMDA5QzcyRTlGRiIsInNjcCI6Ik1haWwuUmVhZCBNYWlsLlNlbmQiLCJzdWIiOiJ4SF9JNzl0bFRwbGI0WG41RktKSHZ6VTBkU2pJOUNBaDVCaElWTnljMTBNIiwidGlkIjoiN2Q5MDNmMzktOTFkZi00ZWYxLThkNjQtNzE0MzA5OWExNWYwIiwidW5pcXVlX25hbWUiOiJhdXRvYmlsbEB3ZWJhbGl2ZS5jb20uYXUiLCJ1cG4iOiJhdXRvYmlsbEB3ZWJhbGl2ZS5jb20uYXUiLCJ2ZXIiOiIxLjAifQ.a9RnBzxlChE8-_kfTcYuQy2lbpVsZOKIpn-fmSjePi5oiX4aPL-SZ6xL9rwdjL4SWeOyiDLHmVs3jhEbHkEIZhD4aqzbvqTovQOUluyHOAHVjQJyRc6AV6g-WP4jmbCDVOKFvvq9llZ13Srihvua1wFCM5z-nDZsIVY0LzTeew8-ZTM5trVEG9QtyR_UmlgLgwbIOl9PWz0MvFcCLbFiZQ8-1zGje8oL_fbm8vFtRdP_bNS6OzyatupFvAQRM4RhFQYHhuxKCVzI35JoEWfhHtUZAReTYwRfBULEJuT_CIkC0G7DyWJR1IRVnaYSWagvj93tOZtIaU-OMSsovmYEtg";
}

function runCurl($url, $post = null, $headers = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, $post == null ? 0 : 1);
    if($post != null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    if($headers != null) {
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if($http_code >= 400) {
        echo "Error executing request to Office365 api with error code=$http_code<br/><br/>\n\n";
        echo "<pre>"; print_r($response); echo "</pre>";
        die();
    }
    return array("code" => $http_code, "response" => $response);
}
?>

7 comments:

  1. Thank you for the code excerpt. It works very well and has saved me a lot of time. :)

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Thanks, This code made my day! This code is even relevant and working in Feb2020.

    ReplyDelete
  4. access_token itshould be dynamic

    ReplyDelete
  5. access_token itshould be dynamic

    ReplyDelete
  6. great article, it would be helpful if you share step by step

    ReplyDelete