send mail through Gmail API

reference
howto – http://developers.google.com/gmail/api/auth/web-server
code snippet – http://stackoverflow.com/q/26627755
code snippet – http://github.com/google/google-api-php-client/issues/376
code snippet – http://stackoverflow.com/questions/28122074/gmail-api-emails-bouncing
Users.messages-> send – http://developers.google.com/gmail/api/v1/reference/users/messages/send


 
similar – Manipulate Calendar through Google API – https://www.pipiscrew.com/2015/05/php-manipulate-calendar-through-google-api/
 

BlueHost blocked the feature to send mail by another SMTP (PHPMailer no working etc.)

SOLUTION is one! Use GMAIL API!!!

 
-as 01/04/2015
-goto http://console.developers.google.com/
-select a project, or create a new one. In the sidebar on the left, expand APIs & auth. Next, click APIs. In the list of APIs, enable Gmail API.
 

 
-in the sidebar on the left, select Credentials > OAuth – Create new Client ID, setup as :
 

 
-now we have Client ID + Client secret thats great!

-download http://github.com/google/google-api-php-client ZIP
-goto http://x.com/pipis2/ extract the folder Google that is inside google-api-php-client-master.zip\google-api-php-client-master\src, so no we have

-create an index.php and paste :

//index.php gmail api send mail
//code is dirty but working!
<?php

session_start();

  require_once 'Google/autoload.php'; // or wherever autoload.php is located

	$client = new Google_Client();
	$client->setClientId("x-x.apps.googleusercontent.com");
	$client->setClientSecret("xyxyxyxyxy");
	$client->setRedirectUri("https://x.com/pipis2/");
	$client->setAccessType('offline');
	$client->setApprovalPrompt('force');

	$client->addScope("https://mail.google.com/");
	$client->addScope("https://www.googleapis.com/auth/gmail.compose");
	$client->addScope("https://www.googleapis.com/auth/gmail.modify");
	$client->addScope("https://www.googleapis.com/auth/gmail.readonly");


if (isset($_REQUEST['code'])) {
	//land when user authenticated
	$code = $_REQUEST['code'];
	$client->authenticate($code);
	
	$_SESSION['gmail_access_token'] = $client->getAccessToken();
	
	header("Location: https://x.com/pipis2/");
}

//$isAccessCodeExpired = $client->isAccessTokenExpired();


//if (isset($_SESSION['gmail_access_token']) &amp;&amp; !empty($_SESSION['gmail_access_token']) &amp;&amp; $isAccessCodeExpired != 1) {
if (isset($_SESSION['gmail_access_token'])) {
	//gmail_access_token setted;
	
	$boundary = uniqid(rand(), true);

    $client->setAccessToken($_SESSION['gmail_access_token']);            
    $objGMail = new Google_Service_Gmail($client);
    
    $subjectCharset = $charset = 'utf-8';
    $strToMailName = 'To User Name';
    $strToMail = 'yourmail@yourmail@93.com';
    $strSesFromName = 'From User Name';
    $strSesFromEmail = 'yourmail@yourmail@93.com';
    $strSubject = 'Test mail using GMail API' . date('M d, Y h:i:s A');

    $strRawMessage .= 'To: ' . encodeRecipients($strToMailName . " <" . $strToMail . ">") . "\r\n";
    $strRawMessage .= 'From: '. encodeRecipients($strSesFromName . " <" . $strSesFromEmail . ">") . "\r\n";

    $strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n";
    $strRawMessage .= 'MIME-Version: 1.0' . "\r\n";
    $strRawMessage .= 'Content-type: Multipart/Alternative; boundary="' . $boundary . '"' . "\r\n";

// 	$strRawMessage .= "\r\n--{$boundary}\r\n";
//    $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";            
//    $strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";            
//    $strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
//    $strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
//    $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
//    $strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
//    $strRawMessage .= '--' . $boundary . "\r\n";

    $strRawMessage .= "\r\n--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: text/plain; charset=' . $charset . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: 7bit' . "\r\n\r\n";
    $strRawMessage .= "this is a test!" . "\r\n";

    $strRawMessage .= "--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
    $strRawMessage .= "this is a tes2t!" . "\r\n";
    
    //Send Mails
    //Prepare the message in message/rfc822
    try {
        // The message needs to be encoded in Base64URL
        $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
        $msg = new Google_Service_Gmail_Message();
        $msg->setRaw($mime);
        $objSentMsg = $objGMail->users_messages->send("me", $msg);

        print('Message sent object');
        print($objSentMsg);

    } catch (Exception $e) {
        print($e->getMessage());
        unset($_SESSION['gmail_access_token']);
    }
}
else {
    // Failed Authentication
    if (isset($_REQUEST['error'])) {
        //header('Location: ./index.php?error_code=1');
        echo "error auth";
    }
    else{
        // Redirects to google for User Authentication
        $authUrl = $client->createAuthUrl();
        header("Location: $authUrl");
    }
}

function encodeRecipients($recipient){
    $recipientsCharset = 'utf-8';
    if (preg_match("/(.*)<(.*)>/", $recipient, $regs)) {
        $recipient = '=?' . $recipientsCharset . '?B?'.base64_encode($regs[1]).'?= <'.$regs&#91;2&#93;.'>';
    }
    return $recipient;
}
 

 
 
optimized (utf8 – subject and body safe) :

//index-opt.php
<?php

session_start();

  require_once 'Google/autoload.php'; // or wherever autoload.php is located

	$client = new Google_Client();
//your gmail tied ClientId (aka Google Console)
	$client->setClientId("x-y.apps.googleusercontent.com");
	$client->setClientSecret("x");
//your gmail tied ClientId (aka Google Console)
	$client->setRedirectUri("https://www.x.com/pipis2");
	$client->setAccessType('offline');
	$client->setApprovalPrompt('force');

	$client->addScope("https://mail.google.com/");
	$client->addScope("https://www.googleapis.com/auth/gmail.compose");
	$client->addScope("https://www.googleapis.com/auth/gmail.modify");
	$client->addScope("https://www.googleapis.com/auth/gmail.readonly");


if (isset($_REQUEST['code'])) {
	//land when user authenticated
	$code = $_REQUEST['code'];
	$client->authenticate($code);
	
	$_SESSION['gmail_access_token'] = $client->getAccessToken();
	
	header("Location: https://www.x.com/pipis2");
}

//$isAccessCodeExpired = $client->isAccessTokenExpired();


//if (isset($_SESSION['gmail_access_token']) &amp;&amp; !empty($_SESSION['gmail_access_token']) &amp;&amp; $isAccessCodeExpired != 1) {
if (isset($_SESSION['gmail_access_token']) &amp;&amp; !empty($_SESSION['gmail_access_token']) ) {

    $client->setAccessToken($_SESSION['gmail_access_token']);            
    $objGMail = new Google_Service_Gmail($client);

    $strSubject = 'Αυτό είναι Test mail using GMail API' . date('M d, Y h:i:s A');

	$strRawMessage = "From: Human Test <joe@gmail.com>\r\n";
	$strRawMessage .= "To: 93 Robot <joe@yahoo.com>\r\n";
    $strRawMessage .= 'Subject: =?utf-8?B?' . base64_encode($strSubject) . "?=\r\n";
	$strRawMessage .= "MIME-Version: 1.0\r\n";
	$strRawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
	$strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
	$strRawMessage .= "this <b>is a</b> τηισ είς α τεστ tes2t!\r\n";

    //Users.messages->send - Requires -> Prepare the message in message/rfc822
    try {
        // The message needs to be encoded in Base64URL
        $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
        $msg = new Google_Service_Gmail_Message();
        $msg->setRaw($mime);

        //The special value **me** can be used to indicate the authenticated user.
        $objSentMsg = $objGMail->users_messages->send("me", $msg);

        print('Message sent object');
        print($objSentMsg);

    } catch (Exception $e) {
        print($e->getMessage());
        unset($_SESSION['gmail_access_token']);
    }
}
else {
    // Failed Authentication
    if (isset($_REQUEST['error'])) {
        //header('Location: ./index.php?error_code=1');
        echo "error auth";
    }
    else{
        // Redirects to google for User Authentication
        $authUrl = $client->createAuthUrl();
        header("Location: $authUrl");
    }
}

 


 

Automate process (no user interaction) :

	$client->setAccessType('offline');
	$client->setApprovalPrompt('force');

source – http://developers.google.com/accounts/docs/OAuth2WebServer#offline

In some cases, your application may need to access a Google API when the user is not present. Examples of this include backup services and applications that make blogger posts exactly at 8am on Monday morning. This style of access is called offline, and web server applications may request offline access from a user. The normal and default style of access is called online.

If is the first time the application has exchanged an authorization code for a user, then the response includes an access token and a refresh token, as shown below:

{
  "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer",
  "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

Important: When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the approval_prompt parameter in the authorization code request, and set the value to force.
 
 
^apply to code :

//index-opt-automated.php
<?php
 
session_start();
 
  require_once 'Google/autoload.php'; // or wherever autoload.php is located
 
    $client = new Google_Client();
//your gmail tied ClientId (aka Google Console)
    $client->setClientId("x-y.apps.googleusercontent.com");
    $client->setClientSecret("x");
//your gmail tied ClientId (aka Google Console)
    $client->setRedirectUri("https://www.x.com/pipis2");
    $client->setAccessType('offline');
    $client->setApprovalPrompt('force');
 
    $client->addScope("https://mail.google.com/");
    $client->addScope("https://www.googleapis.com/auth/gmail.compose");
    $client->addScope("https://www.googleapis.com/auth/gmail.modify");
    $client->addScope("https://www.googleapis.com/auth/gmail.readonly");
 
//if (isset($_REQUEST['code'])) {
//    //land when user authenticated
//    $code = $_REQUEST['code'];
//    $client->authenticate($code);
// 
//    $_SESSION['gmail_access_token'] = $client->getAccessToken();
// 
//	echo $_SESSION['gmail_access_token'];
//	exit;
//    header("Location: https://www.x.com/pipis2");
//}
 
$_SESSION['gmail_access_token'] = '{"access_token":"x.y-t-o","token_type":"Bearer","expires_in":3600,"refresh_token":"a\/n-m","created":-9}';

//$isAccessCodeExpired = $client->isAccessTokenExpired();
 
 
//if (isset($_SESSION['gmail_access_token']) &amp;&amp; !empty($_SESSION['gmail_access_token']) &amp;&amp; $isAccessCodeExpired != 1) {
if (isset($_SESSION['gmail_access_token']) &amp;&amp; !empty($_SESSION['gmail_access_token']) ) {
 
    $client->setAccessToken($_SESSION['gmail_access_token']);
    $objGMail = new Google_Service_Gmail($client);
 
    $strSubject = 'Αυτό είναι Test mail using GMail API' . date('M d, Y h:i:s A');
 
    $strRawMessage = "From: Human Test <joe@gmail.com>\r\n";
    $strRawMessage .= "To: 93 Robot <joe@yahoo.com>\r\n";
    $strRawMessage .= 'Subject: =?utf-8?B?' . base64_encode($strSubject) . "?=\r\n";
    $strRawMessage .= "MIME-Version: 1.0\r\n";
    $strRawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
    $strRawMessage .= "this <b>is a</b> τηισ είς α τεστ tes2t!\r\n";
 
    //Users.messages->send - Requires -> Prepare the message in message/rfc822
    try {
        // The message needs to be encoded in Base64URL
        $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
        $msg = new Google_Service_Gmail_Message();
        $msg->setRaw($mime);
 
        //The special value **me** can be used to indicate the authenticated user.
        $objSentMsg = $objGMail->users_messages->send("me", $msg);
 
        print('Message sent object');
        print($objSentMsg);
 
    } catch (Exception $e) {
        print($e->getMessage());
        unset($_SESSION['gmail_access_token']);
    }
}
else {
    // Failed Authentication
    if (isset($_REQUEST['error'])) {
        //header('Location: ./index.php?error_code=1');
        echo "error auth";
    }
    else{
        // Redirects to google for User Authentication
        $authUrl = $client->createAuthUrl();
        header("Location: $authUrl");
    }
}
?>

1-line 29+30 : we run it once to get the ‘access token and a refresh token’
2-we remark 22-32 and set to a session variable the ‘access token and a refresh token’ we got at step1

By: |01/04/2015|categories: