Gmail: Remove Label from Email Message
Removes labels from an email message in Gmail. You can remove multiple labels at once. When you remove multiple labels you should write one label per line.
Configs
  • C1: OAuth2 Setting *
  • C2: Message ID *
  • C3: Labels to remove *

Notes

  • This modelling element is for Google Workspace accounts only. You cannot use it with a general user account (gmail.com).
  • It is required that the Google Workspace Administrator has marked the corresponding OAuth app as trusted. If the OAuth app is not trusted, you cannot use this modelling element.
    • The client ID of the corresponding OAuth app is 13039123046-t87nmrj499ffoa58asehks3asajvgqnh.apps.googleusercontent.com .
  • Message ID is not displayed in Gmail. Use the Message ID retrieved by Start: Gmail: Message Received.
  • In addition to user-created labels, system labels such as INBOX, UNREAD and STARRED are also supported. For the list of system labels see the Gmail API Guide.

Capture

See also

Appendix

  • gmail-message-label-remove.xml (C) Questetra, Inc. (MIT License)
    • If you are using Professional, you can modify the contents of this file and use it as your own add-on
Script (click to open)


// OAuth2 config sample at [OAuth 2.0 Setting]
// - Authorization Endpoint URL: https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force
// - Token Endpoint URL: https://oauth2.googleapis.com/token
// - Scope: https://www.googleapis.com/auth/gmail.modify
// - Consumer Key: (Get by Google Developer Console)
// - Consumer Secret: (Get by Google Developer Console)

main();
function main(){
  //// == 工程コンフィグ・ワークフローデータの参照 / Config & Data Retrieving ==
  const auth = configs.get("conf_auth");
  const messageId = engine.findData( configs.getObject("conf_messageId") );
  const labels = retrieveLabels();

  //// == 演算 / Calculating ==
  const apiUri = determineApiUri( messageId );
  const labelIds = getLabelIds( auth, labels );
  removeLabels( apiUri, auth, labelIds );
}

/**
  * ワークフローデータからラベルを読み出す
  * ラベルの設定がない場合はエラー
  * @return {Array<String>} labels ラベル一覧
  */
function retrieveLabels() {
  const labels = configs.get('conf_label').split('\n')
    .map(label => label.trim())
    .filter(label => label !== '');
  // データ項目に改行のみ等、ラベルの設定がない場合はエラー
  if (labels.length === 0) {
    throw "No labels to remove are set.";
  }
  return labels;
}

/**
  * Gmail のメール編集の URI を決定する
  * メール ID が空であればエラーとする
  * @param {String} messageId  メール ID
  * @return {String} apiUri  API の URI
  */
function determineApiUri( messageId ) {
  if ( messageId === "" || messageId === null ) {
    throw "Message ID is empty.";
  }
  const apiUri = `https://gmail.googleapis.com/gmail/v1/users/me/messages/${encodeURI(messageId)}/modify`;
  return apiUri;
}

/**
 * ラベルからラベル ID を取得する
 * @param {String} auth 認証設定
 * @param {Array<String>} labels ラベル一覧
 * @return {Array<String>} ラベル ID の一覧
 */
function getLabelIds( auth, labels ) {
    const response = httpClient.begin()
        .authSetting(auth)
        .get('https://gmail.googleapis.com/gmail/v1/users/me/labels');
    const responseJson = response.getResponseAsString();
    const status = response.getStatusCode();
    if (status >= 300) {
        const accessLog = `--- users.labels.list --- ${status}\n${responseJson}\n`;
        engine.log(accessLog);
        throw `Failed to get labels. status: ${status}`;
    }

    const json = JSON.parse(responseJson);
    let found = json.labels
        .filter(label => labels.includes(label.name));
    const foundLabels = found.map(label => label.name);
    const notFoundLabels = labels.filter(label => !foundLabels.includes(label));
    if (notFoundLabels.length > 0) {
        const accessLog = `--- users.labels.list --- ${status}\n${responseJson}\n`;
        engine.log(accessLog);
        // id が見つからない label がある場合、エラーをスロー
        throw `label ids of ${notFoundLabels.join(', ')} not found`;
    }
    return found.map(label => label.id);
}

/**
  * Gmail REST API にメール編集の POST リクエストを送信し、ラベルを除去する
  * @param {String} apiUri  API の URI
  * @param {String} auth  認証設定名
  * @param {Array<String>} labelIds  ラベル ID の一覧
  */
function removeLabels( apiUri, auth, labelIds ) {
  const body = {
    "removeLabelIds": labelIds
  };
  const response = httpClient.begin()
    .authSetting( auth )
    .body(JSON.stringify(body), "application/json; charset=UTF-8")
    .post( apiUri );

  // when error thrown
  const responseJson = response.getResponseAsString();
  const status = response.getStatusCode();
  if (status >= 300) {
    const accessLog = `---POST request--- ${status}\n${responseJson}\n`;
    engine.log( accessLog );
    throw `Failed to remove labels. status: ${status}`;
  }
}

  

1 thought on “Gmail: Remove Label from Email Message”

  1. Pingback: Starting a Process Triggered by Receiving a Gmail – Questetra Support

Comments are closed.

%d bloggers like this: