Hakan Baba
Hakan Baba

Reputation: 2035

Is there a way to add multiple labels at once to a Gmail thread in a google app script?

I am trying to add some labels to Gmail threads in a google-app script programmatically.

Using thread.addLabel function right now. Because I am adding multiple labels to many threads, this approach is first slow and second inefficient in quota usage. I have to call thread.allLabel for every label for every thread.

Is there a way to add multiple labels to Gmail threads / messages together? The Gmail API has a thread.modify function that can be used to add multiple labels. Is there something similar in google apps script ?

Upvotes: 0

Views: 800

Answers (1)

Tanaike
Tanaike

Reputation: 201503

You want to add several labels to a thread using Google Apps Script. If my understanding is correct, how about using Gmail API of Advanced Google Services? In GmailApp, I couldn't find methods for adding several labels to a thread. So I propose this. I think that you can achieve it using gmail.users.messages.modify. The sample script is as follows. In order to use this script, please enable Gmail API at Advanced Google Services and API console.

Enable Gmail API v1 at Advanced Google Services

  • On script editor
    • Resources -> Advanced Google Services
    • Turn on Gmail API v1

Enable Gmail API at API console

  • On script editor
    • Resources -> Cloud Platform project
    • View API console
    • At Getting started, click Enable APIs and get credentials like keys.
    • At left side, click Library.
    • At Search for APIs & services, input "Gmail". And click Gmail API.
    • Click Enable button.
    • If API has already been enabled, please don't turn off.

If now you are opening the script editor with the script for using Gmail API, you can enable Gmail API for the project by accessing this URL https://console.cloud.google.com/apis/api/gmail.googleapis.com/overview

Flow of script :

  1. Retrieve label list.
  2. Retrieve label IDs using label names.
  3. Add the labels to a thread.

Sample script :

var userId = "me";
var threadId = "### thread ID ###"; // Please input a thread ID.
var labels = ["### label name 1 ###", "### label name 2 ###"]; // Please input label names here.

var labelList = Gmail.Users.Labels.list(userId).labels;
var labelIds = labels.map(function(e){return labelList.filter(function(f){return f.name == e})[0].id});
Gmail.Users.Messages.modify({"addLabelIds": labelIds}, userId, threadId);

Note :

  • This is a simple sample script. So please modify it to your environment.

References :

If I misunderstand your question, I'm sorry.

Upvotes: 2

Related Questions