1 | |
2 |
|
3 | |
4 | * Search Messages |
5 | * List messages matching a Gmail search query (same operators as the Gmail search box, e.g. `from:alice@example.com is:unread newer_than:7d`). Returns each message's headers, labels and snippet, plus `nextPageToken` for the next page. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Gmail, |
9 | q: string | undefined, |
10 | label_ids: string[] | undefined, |
11 | max_results: number = 25, |
12 | page_token: string | undefined, |
13 | include_spam_trash: boolean = false |
14 | ) { |
15 | const base = "https://gmail.googleapis.com/gmail/v1/users/me/messages" |
16 | const headers = { |
17 | Authorization: `Bearer ${auth.token}`, |
18 | Accept: "application/json", |
19 | } |
20 |
|
21 | const url = new URL(base) |
22 | url.searchParams.append("maxResults", String(max_results)) |
23 | url.searchParams.append("includeSpamTrash", String(include_spam_trash)) |
24 | if (q !== undefined && q !== "") url.searchParams.append("q", q) |
25 | if (page_token !== undefined && page_token !== "") |
26 | url.searchParams.append("pageToken", page_token) |
27 | for (const id of label_ids ?? []) url.searchParams.append("labelIds", id) |
28 |
|
29 | const response = await fetch(url, { headers }) |
30 | if (!response.ok) { |
31 | throw new Error(`${response.status} ${await response.text()}`) |
32 | } |
33 | const list = (await response.json()) as { |
34 | messages?: { id: string }[] |
35 | nextPageToken?: string |
36 | resultSizeEstimate: number |
37 | } |
38 |
|
39 | |
40 | const messages = await Promise.all( |
41 | (list.messages ?? []).map(async ({ id }) => { |
42 | const msgUrl = new URL(`${base}/${id}`) |
43 | msgUrl.searchParams.append("format", "metadata") |
44 | for (const h of ["From", "To", "Cc", "Subject", "Date"]) |
45 | msgUrl.searchParams.append("metadataHeaders", h) |
46 | const r = await fetch(msgUrl, { headers }) |
47 | if (!r.ok) throw new Error(`${r.status} ${await r.text()}`) |
48 | return await r.json() |
49 | }) |
50 | ) |
51 |
|
52 | return { |
53 | messages, |
54 | nextPageToken: list.nextPageToken, |
55 | resultSizeEstimate: list.resultSizeEstimate, |
56 | } |
57 | } |
58 |
|