Posts send mail through Gmail API
Post
Cancel

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 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//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']) && !empty($_SESSION['gmail_access_token']) && $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[2].'>';
    }
    return $recipient;
}

optimized (utf8 - subject and body safe) :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//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']) && !empty($_SESSION['gmail_access_token']) && $isAccessCodeExpired != 1) {
if (isset($_SESSION['gmail_access_token']) && !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 **is a** τηισ είς α τεστ 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) :

1
2
	$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:

1
2
3
4
5
6
{
  "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 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//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']) && !empty($_SESSION['gmail_access_token']) && $isAccessCodeExpired != 1) {
if (isset($_SESSION['gmail_access_token']) && !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 **is a** τηισ είς α τεστ 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</joe@yahoo.com></joe@gmail.com></joe@yahoo.com></joe@gmail.com></’.$regs[2].’></(.*)></’></”></”>

origin - http://www.pipiscrew.com/?p=2773 php-send-mail-through-gmail-api

This post is licensed under CC BY 4.0 by the author.
Contents

Trending Tags