首页 > 解决方案 > 使用 Php 的 Gmail Api 在执行时抛出“权限不足”消息

问题描述

我试图将 Gmail Api 与 PHP 一起使用。我修改了谷歌文档快速入门中给我的代码。我可以从我的 gmail 帐户中获取标签,但是当我尝试发送邮件时,它会引发错误Insufficient Permission。谁能告诉我在 PHP 中使用 Gmail API 发送邮件的正确方法?

<?php
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Gmail API PHP Quickstart');
    $client->setScopes(array(
        "https://www.googleapis.com/auth/plus.login",
        "https://www.googleapis.com/auth/userinfo.email",
        "https://www.googleapis.com/auth/userinfo.profile",
        "https://www.googleapis.com/auth/plus.me"
        ));
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
        echo "\n\n Got the token path";
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        echo "\n\n token expired";
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            echo "\n\n Got the refreshed token";
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
            echo "\n\n Created a new token ";
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
            echo "\n\n directory not created. Directory created";
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
        echo "\n\n got the access token";
    }
    // echo json_encode($client);
    return $client;
}

// Get the API client and construct the service object.
$client = getClient();
echo json_encode($client);
$service = new Google_Service_Gmail($client);
echo json_encode($service);


$user = 'me';
$results = $service->users_labels->listUsersLabels($user);

if (count($results->getLabels()) == 0) {
  print "No labels found.\n";
} else {
  print "Labels:\n";
  foreach ($results->getLabels() as $label) {
    printf("- %s\n", $label->getName());
  }
}

function createMessage($email) {
    echo "\n\n\ncreate message function called";
    $message = new Google_Service_Gmail_Message();
    $email = strtr(base64_encode($email), array('+' => '-', '/' => '_'));
    $message->setRaw($email);
    return $message;
  }

function sendMessage($service, $userId, $message) {
    echo "\n\n\n\n send message called\n\n\n";
      try {
        $message = $service->users_messages->send($userId, $message);
        print 'Message with ID: ' . $message->getId() . ' sent.';
        return $message;
      } catch (Exception $e) {
        print 'An error occurred: ' . $e->getMessage();
      }
    }
$email='<email_address>';
$message = createMessage(<email_address>');

sendMessage($service," <email_address>",$message);

标签: phpapigmail

解决方案


推荐阅读