0

Modify Email

by
Published today

Change a message's state: mark read or unread, flag, set importance, and add or remove categories (labels). Only the options you set are applied; existing categories not listed are kept. Requires Mail.ReadWrite (a connection default).

Script ms_outlook Verified

The script

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

3
/**
4
 * Modify Email
5
 * Change a message's state: mark read or unread, flag, set importance, and add or remove categories (labels). Only the options you set are applied; existing categories not listed are kept. Requires Mail.ReadWrite (a connection default).
6
 */
7
export async function main(
8
  auth: RT.MsOutlook,
9
  message_id: string,
10
  is_read: "keep" | "true" | "false" = "keep",
11
  flag_status: "keep" | "notFlagged" | "flagged" | "complete" = "keep",
12
  importance: "keep" | "low" | "normal" | "high" = "keep",
13
  add_categories: string[] | undefined,
14
  remove_categories: string[] | undefined,
15
  mailbox: string | undefined
16
) {
17
  const base = `https://graph.microsoft.com/v1.0/${
18
    mailbox != null && mailbox !== ""
19
      ? `users/${encodeURIComponent(mailbox)}`
20
      : "me"
21
  }`
22
  const url = `${base}/messages/${encodeURIComponent(message_id)}`
23
  const headers = {
24
    Authorization: `Bearer ${auth.token}`,
25
    "Content-Type": "application/json",
26
    Accept: "application/json",
27
  }
28

29
  const patch: { [key: string]: any } = {}
30
  if (is_read !== "keep") patch.isRead = is_read === "true"
31
  if (flag_status !== "keep") patch.flag = { flagStatus: flag_status }
32
  if (importance !== "keep") patch.importance = importance
33

34
  // categories is replaced as a whole, so merge with what the message has
35
  if (add_categories?.length || remove_categories?.length) {
36
    const current = await fetch(`${url}?$select=categories`, { headers })
37
    if (!current.ok) {
38
      throw new Error(`${current.status} ${await current.text()}`)
39
    }
40
    const { categories } = (await current.json()) as { categories: string[] }
41
    patch.categories = [
42
      ...new Set([...categories, ...(add_categories ?? [])]),
43
    ].filter((c) => !(remove_categories ?? []).includes(c))
44
  }
45

46
  const response = await fetch(url, {
47
    method: "PATCH",
48
    headers,
49
    body: JSON.stringify(patch),
50
  })
51

52
  if (!response.ok) {
53
    throw new Error(`${response.status} ${await response.text()}`)
54
  }
55

56
  return await response.json()
57
}
58