I'm new to this API and currently trying to send email by Gmail. I have Laravel installed and required by composer google/apiclient:"^2.7".
That's how I call create message and send functions
$message = $this->googleApi->createMessage($user->name, $user->email, 'An email', $text);
$client = new Google_Client();
$service = new Google_Service_Gmail($client);
$userId = 'my-google-id.apps.googleusercontent.com'
$sendMessage = $this->googleApi->sendMessage($service, $userid, $message);
class to create message for API:
public function createMessage($sender, $to, $subject, $messageText)
{
$message = new Google_Service_Gmail_Message();
$subjectCharset = $charset = 'utf-8';
$messageBody = 'Hello';
$boundary = uniqid(rand(), true);
$rawMessageString = "From: <{$sender}>\r\n";
$rawMessageString .= "To: <{$to}>\r\n";
$rawMessageString .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($subject) . "?=\r\n";
$rawMessageString .= "MIME-Version: 1.0\r\n";
$rawMessageString .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";
$rawMessageString .= "\r\n--{$boundary}\r\n";
$rawMessageString .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
$rawMessageString .= "Content-Transfer-Encoding: base64" . "\r\n\r\n";
$rawMessageString .= str_replace("\n","",$messageBody)."\r\n";
$rawMessageString .= "--{$boundary}\r\n";
$rawMessage = rtrim(strtr(base64_encode($rawMessageString), '+/', '-_'), '=');
$message->setRaw($rawMessage);
return $message;
}
class to send email:
public function sendMessage($service, $userId, $message)
{
try {
$request = $service->users_messages->send($userId, $message);
return $request;
} catch (Exception $e) {
return 'An error occurred: ' . $e->getMessage();
}
}
But for some reason when I trying to pull this out it responds with
{ "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" } }
I'm sorta stuck. Can you elaborate what it does want from me? ID of client was provided, though it says I'm not unauthenticated.
You need to init the Google_client properly PHP quick start. If its not popping up and requesting authorization then its not working right.
I recommend starting with the quick start first. Once you have that working you should be able to alter it to send mails rather than just list labels.
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Gmail API PHP Quickstart');
$client->setScopes(Google_Service_Gmail::GMAIL_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// 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;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);
// Print the labels in the user's account.
$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());
}
}
Note about gmail api and the send mail scope. Verification for this scope is going to take time as it is done by a third party company. I recommend you start early.