Monday, November 21, 2016

Php parse email body & attachments received from google account by oauth2

Email received from google account using oauth2:


stdClass Object
(
    [id] => 15885340ba6b9ba9
    [threadId] => 15885344ba2b9ba9
    [labelIds] => Array
        (
            [0] => SENT
        )

    [snippet] => Hello bro how are you?Some italic mode text
    [historyId] => 685672
    [internalDate] => 1479703529000
    [payload] => stdClass Object
        (
            [mimeType] => multipart/mixed
            [filename] => 
            [headers] => Array
                (
                    [0] => stdClass Object
                        (
                            [name] => Received
                            [value] => from 48568800665 named unknown by gmailapi.google.com with HTTPREST; Sun, 20 Nov 2016 23:45:29 -0500
                        )

                    [1] => stdClass Object
                        (
                            [name] => Return-Path
                            [value] => pritomkucse@xxx.com
                        )

                    [2] => stdClass Object
                        (
                            [name] => From
                            [value] => xxx.xxx@xxx.com
                        )

                    [3] => stdClass Object
                        (
                            [name] => Reply-To
                            [value] => Reply To <some_reply_address@gmails.com>
                        )

                    [4] => stdClass Object
                        (
                            [name] => MIME-Version
                            [value] => 1.0
                        )

                    [5] => stdClass Object
                        (
                            [name] => Date
                            [value] => Sun, 20 Nov 2016 23:45:29 -0500
                        )

                    [6] => stdClass Object
                        (
                            [name] => Subject
                            [value] => Test email on: 21/11/2016 05:45:23
                        )

                    [7] => stdClass Object
                        (
                            [name] => To
                            [value] => To Address <some_to_address@xxx.com>
                        )

                    [8] => stdClass Object
                        (
                            [name] => CC
                            [value] => CC Address <some_cc_address@xxx.com>
                        )

                    [9] => stdClass Object
                        (
                            [name] => Content-Type
                            [value] => multipart/mixed; boundary="4abf1fca8718965424d6569f69ecf783"
                        )

                    [10] => stdClass Object
                        (
                            [name] => Message-Id
                            [value] => <CAD-od7e+ZAOzrQLU-b4O5ZrLP0x0qEkaYnwNB4gBj60bSbd8DQ@mail.gmail.com>
                        )

                )

            [body] => stdClass Object
                (
                    [size] => 0
                )

            [parts] => Array
                (
                    [0] => stdClass Object
                        (
                            [partId] => 0
                            [mimeType] => text/html
                            [filename] => 
                            [headers] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [name] => Content-Type
                                            [value] => text/html; charset=UTF-8
                                        )

                                    [1] => stdClass Object
                                        (
                                            [name] => Content-Transfer-Encoding
                                            [value] => 7bit
                                        )

                                )

                            [body] => stdClass Object
                                (
                                    [size] => 77
                                    [data] => PGI-SGVsbG8gYnJv.....
                                )

                        )

                    [1] => stdClass Object
                        (
                            [partId] => 1
                            [mimeType] => application/pdf
                            [filename] => My-pdf.pdf
                            [headers] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [name] => Content-Type
                                            [value] => application/pdf; name="My-pdf.pdf"
                                        )

                                    [1] => stdClass Object
                                        (
                                            [name] => Content-Transfer-Encoding
                                            [value] => base64
                                        )

                                    [2] => stdClass Object
                                        (
                                            [name] => Content-Disposition
                                            [value] => attachment; filename="My-pdf.pdf"
                                        )

                                )

                            [body] => stdClass Object
                                (
                                    [attachmentId] => ANGjdJ_iTdTRG38Nwxf8...
                                    [size] => 197132
                                )

                        )

                    [2] => stdClass Object
                        (
                            [partId] => 2
                            [mimeType] => image/png
                            [filename] => My-image.png
                            [headers] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [name] => Content-Type
                                            [value] => image/png; name="My-image.png"
                                        )

                                    [1] => stdClass Object
                                        (
                                            [name] => Content-Transfer-Encoding
                                            [value] => base64
                                        )

                                    [2] => stdClass Object
                                        (
                                            [name] => Content-Disposition
                                            [value] => attachment; filename="My-image.png"
                                        )

                                )

                            [body] => stdClass Object
                                (
                                    [attachmentId] => ANGjdJ9AysXkrs_yEFM0...
                                    [size] => 317154
                                )

                        )

                )

        )

    [sizeEstimate] => 686890
)

Php code to parse email body & attachments:


<?php
function viewEmailById() {
    $id = $_GET["email_by_id"];
    $raw = "";// "format=raw&";
    $fields = "";// "fields=raw&";
    $apiUrl = "https://www.googleapis.com/gmail/v1/users/";
    $apiUrl .= getUserID()."/messages/$id?$raw$fields";
    $apiUrl .= "access_token=".token();
    $result = json_decode(runCurl($apiUrl));

    $message = parseEmail($result->payload->parts);
    if(!file_exists($id)) {
        mkdir($id);
    }
    $link = "";
    foreach($message as $msg) {
        $location = $id."/".$msg["name"];
        $fp = fopen("$location","w");
        fwrite($fp, $msg["body"]);
        fclose($fp);
        $link .= "<a href='".$location."' target='_blank'>".$msg["name"]."</a><br/>";
    }
    echo $link;
}

function parseEmail($email) {
    $id = $_GET["email_by_id"];
    $result = array();
    for($i = 0; $i < count($email); $i++) {
        $part = $email[$i];
        $mime = $part->mimeType;
        $name = $part->filename;
        if(strlen($name) > 0) {
            $file = array();
            $file["type"] = $mime;
            $file["name"] = $name;
            $apiUrl = "https://www.googleapis.com/gmail/v1/users/".getUserID();
            $apiUrl .= "/messages/$id/attachments/".$part->body->attachmentId;
            $apiUrl .= "?access_token=".token();
            $remoteFile = json_decode(runCurl($apiUrl));
            $file["body"] = decodeContent($remoteFile->data);
            array_push($result, $file);
        }
        else if($mime === "text/plain") {
            $file = array();
            $file["type"] = "text";
            $file["name"] = "email_body_plain.html";
            $file["body"] = decodeContent($part->body->data);
            array_push($result, $file);
        }
        else if($mime === "text/html") {
            $file = array();
            $file["type"] = "html";
            $file["name"] = "email_body_html.html";
            $file["body"] = decodeContent($part->body->data);
            array_push($result, $file);
        }
        else if(substr($mime, 0, 9) === "multipart") {
            foreach(parseEmail($part->parts) as $file) {
                array_push($result, $file);
            }
        }
    }
    return $result;
}

function decodeContent($content) {
    return base64_decode(str_replace("-", "+", str_replace("_", "/", $content)));
}

function getUserID() {
    $fromSession = valueFromSession("user_id");
    if($fromSession) {
        return $fromSession;
    }
    else {
        $apiUrl = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json";
        $apiUrl .= "&access_token=".token();
        $result = json_decode(runCurl($apiUrl));
        $_SESSION["user_id"] = $result->id;
        return $_SESSION["user_id"];
    }
}

function valueFromSession($name) {
    if(isset($_SESSION[$name])) {
        return $_SESSION[$name];
    }
    return null;
}

function token() {
    return "return your access token from here";
}

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);
    }
    $result = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $test = json_decode($result);
    if((isset($test->error) && $test->error->code == 401) || $httpcode == 401) {
        if(!valueFromSession("redirected")) {
            $_SESSION["redirected"] = true;
            refreshToken();
            header("Refresh:0");
            die();
        }
        else {
            $_SESSION["redirected"] = null;
            echo "Error getting data from google api, reload page to try again";
            die();
        }
    }
    else {
        $_SESSION["redirected"] = null;
    }
    return $result;
}
?>

No comments:

Post a Comment