1

I have been searching for Google documentation to send a mail using gmail oauth 2 credentials. I just created a new project in console.developers.google and enabled gmail using gmail api. I created oauth credentials and even configured them in consent screen. But I am unable to send the mail I just get the following response whenever I run my php file on the server.

An error occurred: {
"error": {
"errors": [
{
 "domain": "global",
 "reason": "insufficientPermissions",
 "message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}

I tried executing the following code

<?php
require __DIR__ . '/vendor/autoload.php';
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Send mail');
$client->setSubject('Verification mail');
$client->setScopes(Google_Service_Gmail::GMAIL_READONLY);
$client->setAuthConfig('client_secret.json');
$client->setAccessType(["https://www.googleapis.com/auth/gmail.compose"]);
$credentialsPath = expandHomeDirectory('credentials.json');
if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
    if (!file_exists(dirname($credentialsPath))) {
        mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath,     json_encode($client->getAccessToken()));
}
return $client;
}
function expandHomeDirectory($path)
{
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
$client = getClient();
$service = new Google_Service_Gmail($client);
try {
    $strSubject = "Verificaion mail";
    $strRawMessage = "From: Me<rammanojpotla1608@gmail.com>\r\n";
    $strRawMessage .= "To: manoj<rammanoj.potla@gmail.com>\r\n";
    $strRawMessage .= "CC: rammanoj<rammanojpotla1608@gmail.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: base64" . "\r\n\r\n";
    $strRawMessage .= "A simple verification mail!" . "\r\n";
    $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
    $msg = new Google_Service_Gmail_Message();
    $msg->setRaw($mime);
    $service->users_messages->send("me", $msg);
} catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
}
?>

can anyone provide a better explanation of above code along with the reason for the error. Thanks!

rammanoj
  • 479
  • 8
  • 26

2 Answers2

1

I guess the error is due to the access type when I changed the access type it gave me an another error. I guess it is raising an error saying that there are not permissions to access your account. This might be due to giving a wrong access token in crdentials.json file or may be because of expiry of access token. However minimizing the above code. I tried understanding and wrote a simple one.

<?php
require __DIR__ . '/vendor/autoload.php';
 $client = new Google_Client();
 $client->setScopes(Google_Service_Gmail::GMAIL_COMPOSE  );
 $client->setAuthConfig('client_secret.json');
 $credentialsPath = __DIR__.'/credentials.json';
 if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
 } else {
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
    if (!file_exists(dirname($credentialsPath))) {
        mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
 }
 $client->setAccessToken($accessToken);
 if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath,   json_encode($client->getAccessToken()));
}
$service = new Google_Service_Gmail($client);
try {
    $strSubject = "Verificaion mail";
    $strRawMessage = "From: Me<rammanojpotla1608@gmail.com>\r\n";
    $strRawMessage .= "To: manoj<rammanoj.potla@gmail.com>\r\n";
    $strRawMessage .= "CC: rammanoj<rammanojpotla1608@gmail.com>\r\n";
    $strRawMessage .= "Subject: =?utf-8?B?" . base64_encode($strSubject) .     "?=\r\n";
    $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
    $msg = new Google_Service_Gmail_Message();
    $msg->setRaw($mime);
    $service->users_messages->send("me", $msg);
    echo "mail sent";
} catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
}

?>

Google_client creates a new google client. Setscopes are need to define the type of operations you are going to perform with the access specified or given to you. Initially, it checks if file named credentials.json is there or not. If it is there it accesses the access_token of the user and perform the desired operation. Here my operation is to send mail using gmail api. So, I created a new Google_Service_Gmail class to perform it. If there is no credentials.json file then it accesses the client_secret.json file that contain the client_id and client_secrent. Using both of them you can generate your access token.

rammanoj
  • 479
  • 8
  • 26
0

Make sure that you have specified several different scope when you authorized a gmail service client. You can find the list here.

See also this SO post for further discussion about the error.

MαπμQμαπkγVπ.0
  • 5,887
  • 1
  • 27
  • 65