0

Modify Labels

by
Published today

Add or remove labels on Gmail messages (archive, mark read, star, trash, apply labels).

Script gmail Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 4 hours ago
1
//native
2

3
export type DynMultiselect_add_label_ids = string[]
4
export type DynMultiselect_remove_label_ids = string[]
5

6
async function listLabels(auth: RT.Gmail) {
7
  const response = await fetch(
8
    "https://gmail.googleapis.com/gmail/v1/users/me/labels",
9
    {
10
      headers: {
11
        Authorization: `Bearer ${auth.token}`,
12
        Accept: "application/json",
13
      },
14
    }
15
  )
16
  if (!response.ok) {
17
    throw new Error(`${response.status} ${await response.text()}`)
18
  }
19
  const { labels } = (await response.json()) as {
20
    labels: { id: string; name: string }[]
21
  }
22
  return labels.map((l) => ({
23
    value: l.id,
24
    label: l.name === l.id ? l.id : `${l.name} (${l.id})`,
25
  }))
26
}
27

28
// Dropdowns of the mailbox's system and user labels.
29
export async function add_label_ids(auth: RT.Gmail) {
30
  return listLabels(auth)
31
}
32
export async function remove_label_ids(auth: RT.Gmail) {
33
  return listLabels(auth)
34
}
35

36
/**
37
 * Modify Labels
38
 * Add and/or remove labels on up to 1000 messages at once. Covers archive (remove INBOX), mark read (remove UNREAD), mark unread (add UNREAD), star (add STARRED), trash (add TRASH) and applying user labels.
39
 */
40
export async function main(
41
  auth: RT.Gmail,
42
  message_ids: string[],
43
  add_label_ids: DynMultiselect_add_label_ids | undefined,
44
  remove_label_ids: DynMultiselect_remove_label_ids | undefined
45
) {
46
  const response = await fetch(
47
    "https://gmail.googleapis.com/gmail/v1/users/me/messages/batchModify",
48
    {
49
      method: "POST",
50
      headers: {
51
        Authorization: `Bearer ${auth.token}`,
52
        "Content-Type": "application/json",
53
        Accept: "application/json",
54
      },
55
      body: JSON.stringify({
56
        ids: message_ids,
57
        addLabelIds: add_label_ids ?? [],
58
        removeLabelIds: remove_label_ids ?? [],
59
      }),
60
    }
61
  )
62
  if (!response.ok) {
63
    throw new Error(`${response.status} ${await response.text()}`)
64
  }
65

66
  // batchModify returns an empty body on success.
67
  return { success: true }
68
}
69