Showing posts with label google oauth2. Show all posts
Showing posts with label google oauth2. Show all posts

Sunday, December 18, 2016

Send Email Using Google OAuth & Java

Download source code & required jars from here

For get access token & google user id click here


package com.pkm.google_auth;

import com.google.api.client.googleapis.GoogleUtils;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.MessagePartHeader;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.ByteArrayOutputStream;
import java.util.Properties;

/**
 * Created by pritom on 18/12/2016.
 */
public class SendMail {
    private static final String USER_ID = "118224585672607576118";
    private static final String ACCESS_TOKEN = "ya29.Ci-4A700L53csid7qv6786780mbRqI8hdwesj7H2RSRnBizwfWFUY0pzYsx_xa-XZA";

    public static void main(String[] args) throws Exception {
        sendMail();
    }

    private static void sendMail() throws Exception {
        Properties props = new Properties();
        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {

        });
        MimeMessage message = new MimeMessage(mailSession);

        message.setSubject("Test subject", "UTF-8");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("pritom@xxxxx.com", "Pritom Kumar"));

        Multipart multipart = new MimeMultipart();
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent("<DIV><B>BOLD HTML BODY</B></DIV>", "text/html");
        multipart.addBodyPart(messageBodyPart);

        message.addHeader("CUSTOM_HEADER_1", "CUSTOM_HEADER_1_VALUE");
        message.addHeader("CUSTOM_HEADER_2", "CUSTOM_HEADER_2_VALUE");

        message.setContent(multipart );

        GoogleCredential credential = new GoogleCredential().setAccessToken(ACCESS_TOKEN);
        Gmail gmail = new Gmail.Builder(_createHttpTransport(), _createJsonFactory(), credential).build();

        com.google.api.services.gmail.model.Message email = createMessageWithEmail(message);
        email = gmail.users().messages().send(USER_ID, email).execute();
        String emailID = email.getId(), messageID = getUniqueMessageIDByEMailId(emailID);
        System.out.println("EMAIL_SEND_WITH_GOOGLE_MAIL_ID=" + emailID);
        System.out.println("EMAIL_SEND_WITH_UNIQUE_MAIL_ID=" + messageID);
    }

    private static String getUniqueMessageIDByEMailId(String emailID) throws Exception {
        GoogleCredential credential = new GoogleCredential().setAccessToken(ACCESS_TOKEN);
        Gmail gmail = new Gmail.Builder(_createHttpTransport(), _createJsonFactory(), credential).build();
        com.google.api.services.gmail.model.Message message = gmail.users().messages().get(USER_ID, emailID).execute();
        for (MessagePartHeader messagePartHeader : message.getPayload().getHeaders()) {
            if (messagePartHeader.getName().equalsIgnoreCase("Message-ID")) {
                emailID = messagePartHeader.getValue().substring(1, messagePartHeader.getValue().length() - 1);
            }
        }
        return emailID;
    }

    private static com.google.api.services.gmail.model.Message createMessageWithEmail(MimeMessage email) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        email.writeTo(baos);
        String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
        com.google.api.services.gmail.model.Message message = new com.google.api.services.gmail.model.Message();
        message.setRaw(encodedEmail);
        return message;
    }

    private static HttpTransport _createHttpTransport() throws Exception {
        return new NetHttpTransport.Builder()
                .trustCertificates(GoogleUtils.getCertificateTrustStore())
                .build();
    }

    private static JsonFactory _createJsonFactory() {
        return new JacksonFactory();
    }
}

Thursday, November 24, 2016

Php read email & attachments from google using oauth

You can get access token & other details to perform this action:
http://pritomkumar.blogspot.com/2016/11/using-oauth-20-for-google-client-side.html

Code snippet to read email & attachments from google using oauth

<?php
session_start();
init();
if(isset($_GET["email_id"])) {
    email_details();
}
else if(isset($_GET["email_attachment"])) {
    email_attachment();
}
else {
    list_email();
}

function init() {
    $_SESSION["google_user_id"] = "11822454346345607576118";
    $_SESSION["access_token"] = "ya29.CjCgA8bf_BCrsdfsdfsdfsdf5orH3cvbMMzQY0RX8NUrbgpNhm9oXHyAAZ0WF3Jid4WwQ";

    /* Permissions to read email */
    $_SESSION["scope"] = "https://www.googleapis.com/auth/userinfo.profile"; /* User profile */
    $_SESSION["scope"] .= " https://www.googleapis.com/auth/gmail.readonly"; /* Read mail */
}

function email_attachment() {
    $id = $_GET["email_attachment"];
    $name = $_GET["name"];
    if (!file_exists("attachments")) {
        mkdir("attachments");
    }

    $apiUrl = "https://www.googleapis.com/gmail/v1/users/".$_SESSION["google_user_id"];
    $apiUrl .= "/messages/$id/attachments/".$id;
    $apiUrl .= "?access_token=".$_SESSION["access_token"];
    $remoteFile = decode_content(json_decode(make_request($apiUrl))->data);
    $file = "attachments/".md5(time()).$name;
    file_put_contents($file, $remoteFile);
    header("Location: $file");
    exit;
}

function email_details() {
    $id = $_GET["email_id"];
    $raw = "";// "format=raw&";
    $fields = "";// "fields=raw&";
    $apiUrl = "https://www.googleapis.com/gmail/v1/users/";
    $apiUrl .= $_SESSION["google_user_id"]."/messages/$id?$raw$fields";
    $apiUrl .= "access_token=".$_SESSION["access_token"];
    //echo $apiUrl; die();
    $result = json_decode(make_request($apiUrl));
    //file_put_contents("raw-email.txt", $result->raw); die();
    //echo "<pre>"; print_r($result); echo "</pre>"; die();

    $message = parse_email($result->payload->parts);
    $link = ""; $html = "";
    foreach($message as $msg) {
        if($msg["type"] == "html") {
            $html = $msg["body"];
        }
        else if($msg["type"] == "text") {
            //you can do anything with text part of email
        }
        else {
            $link .= "<a href='?email_attachment=".$msg["body"]."&name=".$msg["name"]."' target='_blank'>".$msg["name"]."</a><br/>";
        }
    }
    echo "<h3><i>Email Attachments:</i></h3>".$link."<h3><i>Email Body:</i></h3>".trim($html);
}

function parse_email($email) {
    $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;
            $file["body"] = $part->body->attachmentId;
            array_push($result, $file);
        }
        else if($mime === "text/plain") {
            $file = array();
            $file["type"] = "text";
            $file["name"] = "email_body_plain.html";
            $file["body"] = decode_content($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"] = decode_content($part->body->data);
            array_push($result, $file);
        }
        else if(substr($mime, 0, 9) === "multipart") {
            foreach(parse_email($part->parts) as $file) {
                array_push($result, $file);
            }
        }
    }
    return $result;
}

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

function list_email() {
    //gmail api ref page: https://developers.google.com/gmail/api/v1/reference/
    //https://developers.google.com/gmail/api/v1/reference/users/messages/list
    //Searching filtering gmail over oauth2 api using php
    //https://developers.google.com/gmail/api/guides/filtering
    //https://support.google.com/mail/answer/7190?hl=en

    $search = "from:pritom@xxx.com OR from:pritomkucse@gmail.com"; //Search by from address
    $search = "subject:Fwd:"; //Words in the subject line
    $search = "label:sent OR label:starred"; //With certain labels
    $search = "has:attachment"; //Any email with attachments
    $search = "is:important"; //Important mails only
    $search = "is:read"; //For mails those are read already
    $search = "is:unread"; //For mails those are not read yet
    $search = "cc:pritomkucse@gmail.com"; //Emails has specific cc, bcc not allowed
    $search = "after:2016/11/19 AND label:inbox"; //Emails reached inbox after specific date
    $search = "before:2016/04/19 AND label:inbox"; //Emails reached inbox before specific date
    $search = "has:nouserlabels"; //Emails with no labels
    $search = "deliveredto:pritom@xxx.com"; //Emails delivered to some address
    $search = "size:10000"; //Email larger than bytes
    $search = "larger:15M"; //Emails larger than megabytes
    $search = "smaller:1M"; //Emails smaller than megabytes
    $search = "newer_than:1d"; //Emails newer than 1 day (d/m/y)
    $search = "older_than:20d"; //Emails older than 1 day (d/m/y)
    $search = "category:updates"; //Emails in specific category
    $search = "rfc822msgid:2021140448.450273.1479617087520.JavaMail.zimbra@bitmascot.com"; //Specific message by Message-ID
    $search = "!from:@gmail.com"; //Search by not from domain
    $search = "!from:pritomkucse@google.com"; //Search by not from address
    $search = ""; //No filtering

    $maxResults = 10;
    $apiUrl = "https://www.googleapis.com/gmail/v1/users/".$_SESSION["google_user_id"]."/messages?";
    $apiUrl .= "access_token=".$_SESSION["access_token"];
    $apiUrl .= "&maxResults=".$maxResults;
    if(strlen($search) > 0) {
        $apiUrl .= "&q=" . urlencode($search);
    }
    if(isset($_GET["next_page"]) && strlen($_GET["next_page"]) > 0) {
        $apiUrl .= "&pageToken=". $_GET["next_page"];
    }
    $result = json_decode(make_request($apiUrl));
    //echo "<pre>";print_r($result);echo "</pre>";die();

    if(isset($result->messages)) {
        foreach($result->messages as $m) {
            $link = "<a target='_blank' href='?email_id=".$m->id."'>View Message [[".$m->id . "]]</a><br/>";
            echo $link;
        }
    }
    else {
        echo "<pre>"; print_r($result); echo "</pre>"; die();
    }
    if(isset($result->nextPageToken)) {
        echo "<a href='?email=true&next_page=".$result->nextPageToken."'>Next_Page</a>";
    }
}

function make_request($url, $post = null, $headers = null, $returnArray = false) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, $post == null ? 0 : 1);
    if($post != null) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
    }
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSLVERSION, 1);
    if($headers != null) {
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    curl_close($curl);
    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();
    }
    if($returnArray) {
        return array(
            "response" => $response,
            "header_size" => $header_size
        );
    }
    return $response;
}
?>

Monday, November 21, 2016

Php send email using google oauth

You can get access token & other details to perform this action:
http://pritomkumar.blogspot.com/2016/11/using-oauth-20-for-google-client-side.html

Code snippet to send mail using google & php using google oauth


<?php
session_start();
init();

if(isset($_POST["send"])) {
    sendEmail();
}
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["google_user_id"] = "118224585666607576118";
    $_SESSION["access_token"] = "ya29.CjCgdfgdfgdfgROwgDCiVa4ZvfzThKO6I272GJGQoWIEmwvgcNtks0exmxlUmzQ";

    /* Permissions need to send email */
    $_SESSION["scope"] = "https://www.googleapis.com/auth/userinfo.profile"; /* User profile */
    $_SESSION["scope"] .= " https://www.googleapis.com/auth/gmail.send"; /* Send email */
}

function sendEmail() {
    $to = trim($_POST["to"]);
    if (strlen($to) == 0) {
        die("Need email address to send email");
    }

    $cc = "";
    $bcc = "";
    $nl = "\r\n";
    $boundary = md5(date('r', time()));

    $html = trim(utf8_encode($_POST["message"]));

    $attachment_body = "";
    for($i = 0; $i < 6; $i++) {
        if(strlen(trim($_FILES["files"]["name"][$i])) > 0) {
            $content = file_get_contents($_FILES["files"]["tmp_name"][$i]);
            $content = base64_encode($content);
            $this_attachment = "--".$boundary.$nl."Content-Type: ".$_FILES["files"]["type"][$i].$nl;
            $this_attachment .= "Content-Transfer-Encoding: base64$nl";
            $this_attachment .= "Content-Disposition: attachment; filename=\"".$_FILES["files"]["name"][$i]."\"$nl$nl";
            $this_attachment .= $content;

            $attachment_body .= $this_attachment.$nl;
        }
    }

    $message = "Return-Path: pritomkucse@gmail.com$nl".
        "From: your_email@gmail.com$nl".
        "Reply-To: \"Reply To\" <some_reply_address@gmails.com>$nl".
        "MIME-Version: 1.0$nl".
        "Date: ".date('d/m/Y H:i:s')."$nl".
        "Subject: Test email on: ".date("d/m/Y H:i:s")."$nl".
        "To: $to$nl".
        //"CC: \"CC Address\" <$cc>$nl".
        //"BCC: \"BCC Address\" <$bcc>$nl".
        "Content-Type: multipart/mixed; boundary=\"$boundary\"$nl$nl".
        "--$boundary$nl".
        "Content-Type: text/html; charset=iso-8859-1".$nl.
        "Content-Transfer-Encoding: 7bit$nl$nl".
        "$html$nl".
        "$attachment_body".
        "--$boundary--";

    echo "<pre>[[";print_r($message);echo "]]</pre>";

    $submit = array();
    $submit["raw"] = encode_content($message);
    $submit = json_encode($submit);

    $headers = array();
    $headers[] = "Content-Type: application/json";
    $headers[] = "Content-Length: " . strlen($submit);

    $apiUrl = "https://www.googleapis.com/gmail/v1/users/";
    $apiUrl .= $_SESSION["google_user_id"]."/messages/send?format=raw";
    $apiUrl .= "&access_token=".$_SESSION["access_token"];

    $result = runCurl($apiUrl, $submit, $headers);
    echo "<pre>"; echo $result; echo "</pre>"; die();
    /*
    $result will print output as below:
    You can get unique Message-ID by read an email from server
    with email id "1588519a5db4ecfe" (as below)

    HTTP/1.1 200 OK
    Cache-Control: no-cache, no-store, max-age=0, must-revalidate
    Pragma: no-cache
    Expires: Mon, 01 Jan 1990 00:00:00 GMT
    Date: Mon, 21 Nov 2016 04:16:40 GMT
    Vary: X-Origin
    Content-Type: application/json; charset=UTF-8
    X-Content-Type-Options: nosniff
    X-Frame-Options: SAMEORIGIN
    X-XSS-Protection: 1; mode=block
    Server: GSE
    Alt-Svc: quic=":443"; ma=2592000; v="36,35,34"
    Accept-Ranges: none
    Vary: Origin,Accept-Encoding
    Transfer-Encoding: chunked

    {
        "id": "1588519a5db4ecfe",
        "threadId": "1588519a5db4ecfe",
        "labelIds": [
            "SENT"
        ]
    }
    */
}

function encode_content($content) {
    $content = base64_encode($content);
    $content = str_replace("+", "-", $content);
    $content = str_replace("/", "_", $content);
    //$content = rawurlencode($content);
    return $content;
}

function runCurl($url, $post = null, $headers = null) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, $post == null ? 0 : 1);
    if($post != null) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
    }
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSLVERSION, 1);
    if($headers != null) {
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    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 $response;
}
?>

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;
}
?>