Ashwin Orie
Ashwin Orie

Reputation: 1

Gmail API php create label as sublabel

I'm trying to create a gmail label true gmail php api as a sublabel with method: users.labels.create

As in the Gmail api reference creating an normal label (not a sublabel) works good.

Unfortunately creating a sublabel is not discussed in the reference and it's not quite clear if this is possible or not!

// OAuth 2.0 to access Google API

if (isset($_SESSION['access_token']) && $_SESSION['access_token']){
  require_once __DIR__.'/../../../../vendor/autoload.php';
  $client = new Google_Client();
  $client->setAuthConfig('../../../../apps/google-api-scripts/client_secrets.json');
  $client->addScope(Google_Service_Gmail::GMAIL_READONLY);
  $client->addScope(Google_Service_Gmail::GMAIL_SEND);
  $client->addScope(Google_Service_Gmail::GMAIL_MODIFY);
  $client->setAccessToken($_SESSION['access_token']);

  if ($client->getAccessToken() && $client->isAccessTokenExpired()) {
   $client->fetchAccessTokenWithRefreshToken($_COOKIE['refresh_token']);
   $_SESSION['access_token']['access_token'] = json_encode($client->getAccessToken());
   $client->setAccessToken($_SESSION['access_token']);
   }
   // IF there is no access-token found in session
   } else {
   $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/apps/google-api-scripts/oauth2callback.php';
   header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
   }

// Working example to create label:
$service = new Google_Service_Gmail($client);
$user = 'me';
$label = new Google_Service_Gmail_Label();
$label->setName($naamvoordrive);
$results = $service->users_labels->create($user, $label);
$gmaillabelid = $results['id'];

Upvotes: 0

Views: 613

Answers (1)

Kristkun
Kristkun

Reputation: 5963

If you want to create a sub-label, you just need to set the name of your new label in this format:

<parent label name>/<sub-label name>

Here is an example users.labels.create using API explorer

Example Request Body:

{
  "labelListVisibility": "labelShow",
  "messageListVisibility": "show",
  "name": "PARENTLABEL/CHILDLABEL"
}

OUTPUT:

enter image description here


NOTE:

If your parent label name is not existing/invalid. It will create a label based on your set name with "/" rather than a sub-label

Example:

enter image description here

Upvotes: 1

Related Questions