Sample code for 30+ languages & platforms
C++ Requires Chilkat v11.0.0+

Find a Gmail label ID by name

See more GMail REST API Examples

Look up a label using its exact display name, including any parent/child path. Labels and their IDs belong to the authenticated mailbox. Use Gmail’s returned ID when applying a user label to messages.

Authorize the application with https://www.googleapis.com/auth/gmail.labels. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.

Google documentation

Chilkat C++ Downloads

C++
#include <CkJsonObject.h>
#include <CkHttp.h>
#include <CkHttpResponse.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    CkJsonObject token;
    success = token.LoadFile("gmail-token.json");
    if (success != true) {
        std::cout << "Could not read gmail-token.json from the private working directory." << "\r\n";
        return;
    }

    if ((token.JsonTypeOf("access_token") != 1) || (token.StringOfEquals("access_token","",true) == true)) {
        std::cout << "An OAuth access token is required." << "\r\n";
        return;
    }

    CkHttp http;
    http.put_RequireSslCertVerify(true);
    http.put_AuthToken(token.stringOf("access_token"));
    CkHttpResponse resp;
    CkJsonObject reply;
    success = http.HttpNoBody("GET","https://gmail.googleapis.com/gmail/v1/users/me/labels",resp);
    if (resp.get_StatusCode() == 0) {
        std::cout << "Gmail did not return an HTTP response." << "\r\n";
        return;
    }

    if ((success != true) || (resp.get_StatusCode() < 200) || (resp.get_StatusCode() >= 300)) {
        std::cout << "Gmail HTTP " << resp.get_StatusCode() << "\r\n";
        success = reply.Load(resp.bodyStr());
        if (success == true) {
            std::cout << reply.stringOf("error.message") << "\r\n";
        }

        return;
    }

    success = reply.Load(resp.bodyStr());
    if (success != true) {
        std::cout << "Expected a Gmail JSON response." << "\r\n";
        return;
    }

    if (reply.JsonTypeOf("labels") != 4) {
        std::cout << "Expected a list of labels." << "\r\n";
        return;
    }

    CkJsonObject label;
    success = reply.FindRecord2("labels","name","To review",true,label);
    if (success != true) {
        std::cout << "No label with that exact name. Check the name or create the label first." << "\r\n";
        return;
    }

    std::cout << "Label ID: " << label.stringOf("id") << "\r\n";
    }