Reputation: 123
I trying to send an email using Google API
Send email controller look as
public function sendMessage()
{
$client = self::getClient();
$service = new Google_Service_Gmail($client);
$mailer = $service->users_messages;
$message = (new \Swift_Message('Here is my subject'))
->setFrom('[email protected]')
->setTo(['[email protected]' => 'Test Name'])
->setContentType('text/html')
->setCharset('utf-8')
->setBody('<h4>Here is my body</h4>');
$msg_base64 = (new \Swift_Mime_ContentEncoder_Base64ContentEncoder())
->encodeString($message->toString());
$message = new Google_Service_Gmail_Message();
$message->setRaw($msg_base64);
$message = $mailer->send('me', $message);
print_r($message);
}
getClient class:
function getClient()
{
$client = new Google_Client();
$client->setRedirectUri('http://' . 'site.com' . '/oauth2callback.php');
$client->setApplicationName('Gmail API PHP');
$client->setScopes(Google_Service_Gmail::GMAIL_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
return $client;
}
When I'm trying to run this I receiving error:
{ "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED" } }
credentials.json
{"web":{
"client_id":"REDACTED",
"project_id":"project-44",
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
"client_secret":"redacted",
"access_token":"redacted"}}
What can be wrong with my code? When I'm trying to print out $client it displays required data. Or how I shall to login to use it properly without interruptions? I've logged in before(several hours ago).
Upvotes: 1
Views: 1205
Reputation: 509
It looks like you're missing the step where you obtain and/or set the access token or refresh token. In the PHP Quickstart for Gmail, it's this chunk of code:
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} 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));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
To break it down a bit:
$client->createAuthUrl()
)$client->fetchAccessTokenWithAuthCode($authCode)
)$client->setAccessToken($accessToken)
) or save it for future use.In addition to the access token, you'll also want to save the refresh token that gets returned so you don't have to re-login every time ($client->fetchAccessTokenWithRefreshToken($refreshToken)
). If you've gone through this process already, it's possible that your access token expired and you need to either use the refresh token or re-authenticate to get access again.
If you're developing this application for more users than just yourself, you may want to look into managed OAuth platforms like Xkit, where I work. They handle the process of getting authorization, refreshing tokens, etc, along with encrypting the tokens and storing them for each individual user.
Upvotes: 2