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

No comments:

Post a Comment