Я пытался использовать Gmail Api с PHP. Я изменил код, данный мне при быстром запуске документации Google. Я могу получить ярлыки из своей учетной записи Gmail, но при попытке отправить письмо выдает ошибку Недостаточное разрешение . Может кто-нибудь сказать мне правильный способ отправки почты с использованием Gmail API в PHP?
<?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);