@openfn/language-gmail 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,7 +19,8 @@ customize the output.
19
19
  ## Parameters
20
20
 
21
21
  An `options` object can configure the results of the function call. Optional
22
- parameters include: `contents`, `query`, `email`, `processedIds`, `maxResults`
22
+ parameters include: `contents`, `query`, `email`, `processedIds`,
23
+ `maxResults`, `fetchAttachments`
23
24
 
24
25
  ### options.contents
25
26
 
@@ -162,6 +163,34 @@ This works in conjuction with the `options.processedIds` parameter. For example:
162
163
  - this will skip message #1 and resulting dataset will contain a single message
163
164
  #2
164
165
 
166
+ ### options.fetchAttachments
167
+
168
+ Set `fetchAttachments` to `false` to return message IDs and non-attachment
169
+ content without downloading requested file or archive attachments. The default
170
+ is `true`.
171
+
172
+ When downloading is disabled, matched attachments are still reported as
173
+ filename-only objects (without `content`), so a later job can tell which
174
+ messages contain the target attachment:
175
+
176
+ - matched file → `{ filename: 'report.xlsx' }`
177
+ - matched archive → `{ archiveFilename: 'data.zip' }`
178
+ - no match → `null`
179
+
180
+ Pair this with `getMessageById` in a follow-up job to download the attachment
181
+ for exactly the message identified here.
182
+
183
+ ```js
184
+ getContentsFromMessages({
185
+ query: 'after:2026/07/01',
186
+ contents: [
187
+ 'body',
188
+ { type: 'file', name: 'report', file: /\.xlsx$/ },
189
+ ],
190
+ fetchAttachments: false,
191
+ });
192
+ ```
193
+
165
194
  ## Example jobs
166
195
 
167
196
  ```js
@@ -290,14 +319,47 @@ sendMessage({
290
319
  This will send an email with two plain attachments and one ZIP archive
291
320
  containing two files.
292
321
 
293
- # Acquiring an access token
322
+ # `getMessageById`
323
+
324
+ Fetch a single message by its Gmail API message id, instead of searching with
325
+ a query. Takes the same `contents`, `email` and `fetchAttachments` options as
326
+ `getContentsFromMessages`, and returns a single message object (rather than an
327
+ array) on `state.data`.
328
+
329
+ This is the id returned by this adaptor as `messageId` on each result. It is
330
+ not the RFC 822 `Message-ID` header, so it cannot be matched with the
331
+ `rfc822msgid:` search operator.
294
332
 
295
- The Gmail adaptor implicitly uses the Gmail account of the Google account that
296
- is used to authenticate the application.
333
+ This pairs with `getContentsFromMessages`'s `fetchAttachments: false` for a
334
+ two-step pattern: one job lists messages cheaply and records which contain a
335
+ target attachment, and a later job downloads the attachment for one message at
336
+ a time:
337
+
338
+ ```js
339
+ getMessageById($.data.find(m => m.report).messageId, {
340
+ contents: [{ type: 'file', name: 'report', file: /\.xlsx$/ }],
341
+ });
342
+ ```
343
+
344
+ # Authentication
345
+
346
+ This adaptor supports two authentication methods: **OAuth2** and **Service Account**.
347
+
348
+ ## OAuth2
349
+
350
+ **On app.openfn.org:** Click **Sign in with Gmail** in the credential setup form. Authentication is handled for you and no manual token management is needed.
351
+
352
+ **Using the OpenFn CLI locally:** Use the [gcloud CLI](https://cloud.google.com/sdk/docs/install) to print a temporary access token:
353
+
354
+ ```bash
355
+ gcloud auth print-access-token
356
+ ```
357
+
358
+ The Gmail adaptor implicitly uses the Gmail account of the Google account that is used to authenticate the application.
297
359
 
298
360
  Allowing the Gmail adaptor to access a Gmail account is a multi-step process.
299
361
 
300
- ## Create an OAuth 2.0 client ID
362
+ ### Create an OAuth 2.0 client ID
301
363
 
302
364
  Follow the instructions are found here:
303
365
  https://support.google.com/googleapi/answer/6158849
@@ -314,7 +376,7 @@ https://support.google.com/googleapi/answer/6158849
314
376
  - On the resulting popup screen, find and click "DOWNLOAD JSON" and save this
315
377
  file to a secure location.
316
378
 
317
- ## Retrieve an access token
379
+ ### Retrieve an access token
318
380
 
319
381
  - Navigate to
320
382
  [OAuth 2.0 Playground](https://developers.google.com/oauthplayground/).
@@ -344,7 +406,7 @@ https://support.google.com/googleapi/answer/6158849
344
406
  token before it expires** or manually refresh it using the **Refresh access
345
407
  token** button.
346
408
 
347
- ## Configure OpenFn CLI to find the access token
409
+ ### Configure OpenFn CLI to find the access token
348
410
 
349
411
  The Gmail adaptor looks for the access token in the configuration section under
350
412
  `access_token`.
@@ -367,3 +429,20 @@ Example configuration using a workflow:
367
429
  ]
368
430
  }
369
431
  ```
432
+
433
+ ## Service Account
434
+
435
+ Service accounts allow the adaptor to access Gmail without user interaction,
436
+ making them well-suited for automated workflows.
437
+
438
+ > **Important:** Gmail service account access requires **Google Workspace**.
439
+ > It does **not** work with personal Gmail accounts (`@gmail.com`). If your
440
+ > organisation uses personal Google accounts, use the OAuth2 method instead.
441
+
442
+ To create a service account and JSON key file, follow the
443
+ [Google Cloud service account documentation](https://cloud.google.com/iam/docs/service-accounts-create).
444
+ Your OpenFn credential requires the `client_email` and `private_key` fields from the downloaded JSON key file. You can also optionally provide a `subject` field for impersonation -- see [Google's domain-wide delegation guide](https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority) for details.
445
+
446
+ For enabling domain-wide delegation and authorising the required Gmail API
447
+ scopes, see the
448
+ [Google Workspace domain-wide delegation guide](https://support.google.com/a/answer/162106).
package/ast.json CHANGED
@@ -29,7 +29,7 @@
29
29
  },
30
30
  {
31
31
  "title": "state",
32
- "description": "{Array} data - The returned message objects, of the form `{ messageId, contents } `"
32
+ "description": "{Array} data - The returned message objects, of the form `{ messageId, ...contents } `"
33
33
  },
34
34
  {
35
35
  "title": "state",
@@ -52,6 +52,11 @@
52
52
  "title": "example",
53
53
  "description": "getContentsFromMessages(\n {\n query: 'after:15/01/2025',\n contents: [\n 'subject',\n { type: 'file', name: 'metadata', file: 'report.txt'}\n ]\n }\n)",
54
54
  "caption": "Get messages after a specific date, with subject and report.txt attachment"
55
+ },
56
+ {
57
+ "title": "example",
58
+ "description": "getContentsFromMessages(\n {\n query: 'after:2026/07/01',\n contents: [\n 'body',\n { type: 'file', name: 'report', file: /\\.xlsx$/ }\n ],\n fetchAttachments: false\n }\n)",
59
+ "caption": "Get metadata without downloading requested attachments"
55
60
  }
56
61
  ]
57
62
  },
@@ -121,6 +126,67 @@
121
126
  ]
122
127
  },
123
128
  "valid": true
129
+ },
130
+ {
131
+ "name": "getMessageById",
132
+ "params": [
133
+ "messageId",
134
+ "options"
135
+ ],
136
+ "docs": {
137
+ "description": "Downloads contents from a single message of a Gmail account, identified by\nits Gmail API message id.",
138
+ "tags": [
139
+ {
140
+ "title": "public",
141
+ "description": null,
142
+ "type": null
143
+ },
144
+ {
145
+ "title": "function",
146
+ "description": null,
147
+ "name": null
148
+ },
149
+ {
150
+ "title": "param",
151
+ "description": "Gmail API message id to fetch.",
152
+ "type": {
153
+ "type": "NameExpression",
154
+ "name": "string"
155
+ },
156
+ "name": "messageId"
157
+ },
158
+ {
159
+ "title": "param",
160
+ "description": "Customized options including desired contents.",
161
+ "type": {
162
+ "type": "OptionalType",
163
+ "expression": {
164
+ "type": "NameExpression",
165
+ "name": "MessageIdOptions"
166
+ }
167
+ },
168
+ "name": "options"
169
+ },
170
+ {
171
+ "title": "state",
172
+ "description": "{Object} data - The returned message object, of the form `{ messageId, ...contents } `"
173
+ },
174
+ {
175
+ "title": "returns",
176
+ "description": null,
177
+ "type": {
178
+ "type": "NameExpression",
179
+ "name": "Operation"
180
+ }
181
+ },
182
+ {
183
+ "title": "example",
184
+ "description": "getMessageById(\n $.data.messageId,\n {\n contents: [\n { type: 'file', name: 'report', file: /\\.xlsx$/ }\n ]\n }\n)",
185
+ "caption": "Download attachments for a specific message identified by an earlier step"
186
+ }
187
+ ]
188
+ },
189
+ "valid": true
124
190
  }
125
191
  ],
126
192
  "exports": [],
@@ -5,15 +5,35 @@
5
5
  "access_token": {
6
6
  "title": "Access Token",
7
7
  "type": "string",
8
- "description": "Your Gmail access token",
8
+ "description": "Your Gmail OAuth2 access token",
9
9
  "writeOnly": true,
10
10
  "minLength": 1,
11
11
  "examples": [
12
12
  "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjlGWERwYmhax0rZNRlQyU3ZRdVhoODQ2WVR3RUlCdyIsI"
13
13
  ]
14
+ },
15
+ "private_key": {
16
+ "title": "Private Key",
17
+ "type": "string",
18
+ "description": "RSA private key from the Google service account JSON key file. Required for service accounts",
19
+ "writeOnly": true,
20
+ "minLength": 1,
21
+ "examples": ["-----BEGIN RSA PRIVATE KEY-----\nMIIEow..."]
22
+ },
23
+ "client_email": {
24
+ "title": "Client Email",
25
+ "type": "string",
26
+ "description": "Service account email address (e.g. my-app@project-id.iam.gserviceaccount.com). Required for service accounts",
27
+ "minLength": 1,
28
+ "examples": ["my-app@project-id.iam.gserviceaccount.com"]
29
+ },
30
+ "subject": {
31
+ "title": "Subject Email",
32
+ "type": "string",
33
+ "description": "Gmail user to impersonate via domain-wide delegation (e.g. user@yourdomain.com). For service account",
34
+ "examples": ["user@yourdomain.com"]
14
35
  }
15
36
  },
16
37
  "type": "object",
17
- "additionalProperties": true,
18
- "required": ["access_token"]
38
+ "additionalProperties": true
19
39
  }
package/dist/index.cjs CHANGED
@@ -38,6 +38,7 @@ __export(src_exports, {
38
38
  fn: () => import_language_common2.fn,
39
39
  fnIf: () => import_language_common2.fnIf,
40
40
  getContentsFromMessages: () => getContentsFromMessages,
41
+ getMessageById: () => getMessageById,
41
42
  lastReferenceValue: () => import_language_common2.lastReferenceValue,
42
43
  log: () => import_language_common2.log,
43
44
  merge: () => import_language_common2.merge,
@@ -61,6 +62,7 @@ __export(Adaptor_exports, {
61
62
  fn: () => import_language_common2.fn,
62
63
  fnIf: () => import_language_common2.fnIf,
63
64
  getContentsFromMessages: () => getContentsFromMessages,
65
+ getMessageById: () => getMessageById,
64
66
  lastReferenceValue: () => import_language_common2.lastReferenceValue,
65
67
  log: () => import_language_common2.log,
66
68
  merge: () => import_language_common2.merge,
@@ -93,19 +95,26 @@ async function getMessagesResult(userId, query, pageToken) {
93
95
  throw new Error("Error fetching messages: " + error.message);
94
96
  }
95
97
  }
96
- async function getMessageResult(userId, messageId) {
98
+ async function getMessageResult(userId, messageId, format = "full") {
97
99
  var _a, _b;
98
- const { data } = await gmail.users.messages.get({
99
- userId,
100
- id: messageId,
101
- format: "full"
102
- });
103
- return {
104
- userId,
105
- messageId,
106
- parts: (_a = data == null ? void 0 : data.payload) == null ? void 0 : _a.parts,
107
- headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
108
- };
100
+ try {
101
+ const { data } = await gmail.users.messages.get({
102
+ userId,
103
+ id: messageId,
104
+ format,
105
+ ...format === "metadata" && {
106
+ metadataHeaders: ["From", "Date", "Subject"]
107
+ }
108
+ });
109
+ return {
110
+ userId,
111
+ messageId,
112
+ parts: (_a = data == null ? void 0 : data.payload) == null ? void 0 : _a.parts,
113
+ headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
114
+ };
115
+ } catch (error) {
116
+ throw new Error(`Error fetching message ${messageId}: ` + error.message);
117
+ }
109
118
  }
110
119
  function getContentIndicators(defaultContentRequests = [], contentRequests = []) {
111
120
  const contentIndicators = contentRequests.map(getContentIndicator);
@@ -133,12 +142,20 @@ function getContentIndicator(contentRequest) {
133
142
  }
134
143
  return contentIndicator;
135
144
  }
136
- async function getMessageContent(message, desiredContent) {
145
+ async function getMessageContent(message, desiredContent, fetchAttachments = true) {
137
146
  switch (desiredContent.type) {
138
147
  case "archive":
139
- return await getFileFromArchiveFromAttachment(message, desiredContent);
148
+ return await getFileFromArchiveFromAttachment(
149
+ message,
150
+ desiredContent,
151
+ fetchAttachments
152
+ );
140
153
  case "file":
141
- return await getFileFromAttachment(message, desiredContent);
154
+ return await getFileFromAttachment(
155
+ message,
156
+ desiredContent,
157
+ fetchAttachments
158
+ );
142
159
  case "body":
143
160
  return getBodyFromMessage(message, desiredContent);
144
161
  case "from":
@@ -149,6 +166,50 @@ async function getMessageContent(message, desiredContent) {
149
166
  return `Unsupported content type: ${desiredContent.type}`;
150
167
  }
151
168
  }
169
+ function resolveContentPlan(defaultContents, requestedContents, fetchAttachments) {
170
+ const contentIndicators = getContentIndicators(
171
+ defaultContents,
172
+ requestedContents
173
+ );
174
+ const needsFullFormat = contentIndicators.some(
175
+ ({ type }) => type === "body" || type === "file" || type === "archive"
176
+ );
177
+ const messageFormat = needsFullFormat ? "full" : "metadata";
178
+ if (!fetchAttachments) {
179
+ const skippedNames = contentIndicators.filter(({ type }) => type === "file" || type === "archive").map(({ name }) => name);
180
+ if (skippedNames.length) {
181
+ console.log(
182
+ `fetchAttachments is false: skipping attachment downloads for ${skippedNames.join(
183
+ ", "
184
+ )}; matched filenames will still be included in the output`
185
+ );
186
+ }
187
+ }
188
+ return { contentIndicators, messageFormat };
189
+ }
190
+ async function buildMessageContent(userId, messageId, contentIndicators, messageFormat, fetchAttachments) {
191
+ var _a;
192
+ const content = { messageId };
193
+ const messageResult = await getMessageResult(
194
+ userId,
195
+ messageId,
196
+ messageFormat
197
+ );
198
+ for (const contentIndicator of contentIndicators) {
199
+ const messageContent = await getMessageContent(
200
+ messageResult,
201
+ contentIndicator,
202
+ fetchAttachments
203
+ );
204
+ if (messageContent && content[contentIndicator.name]) {
205
+ throw new Error(
206
+ `Duplicate content name detected: ${contentIndicator.name}`
207
+ );
208
+ }
209
+ content[_a = contentIndicator.name] ?? (content[_a] = messageContent);
210
+ }
211
+ return content;
212
+ }
152
213
  async function buildAndSendMessage(message) {
153
214
  const attachments = await parseAttachments(message.attachments);
154
215
  const hasAttachments = attachments && attachments.length > 0;
@@ -218,10 +279,33 @@ async function parseArchiveAttachment(attachment) {
218
279
  content
219
280
  };
220
281
  }
221
- function createConnection(state) {
222
- const { access_token } = state.configuration;
223
- const auth = new import_googleapis.google.auth.OAuth2();
224
- auth.credentials = { access_token };
282
+ async function createConnection(state) {
283
+ const {
284
+ access_token,
285
+ private_key,
286
+ client_email,
287
+ subject,
288
+ scopes = []
289
+ } = state.configuration;
290
+ const mandatoryScopes = [
291
+ "https://mail.google.com/",
292
+ "https://www.googleapis.com/auth/userinfo.email",
293
+ "https://www.googleapis.com/auth/userinfo.profile",
294
+ "openid"
295
+ ];
296
+ let auth;
297
+ if (private_key && client_email) {
298
+ auth = new import_googleapis.google.auth.JWT({
299
+ email: client_email,
300
+ key: private_key,
301
+ scopes: [...mandatoryScopes, ...scopes],
302
+ subject
303
+ });
304
+ await auth.authorize();
305
+ } else {
306
+ auth = new import_googleapis.google.auth.OAuth2();
307
+ auth.credentials = { access_token };
308
+ }
225
309
  gmail = import_googleapis.google.gmail({ version: "v1", auth });
226
310
  return state;
227
311
  }
@@ -229,7 +313,11 @@ function removeConnection(state) {
229
313
  gmail = void 0;
230
314
  return state;
231
315
  }
232
- async function getFileFromArchiveFromAttachment(message, desiredContent) {
316
+ async function getFileFromArchiveFromAttachment(message, desiredContent, fetchAttachments) {
317
+ if (!fetchAttachments) {
318
+ const part = findAttachmentPart(message, desiredContent.archive);
319
+ return part ? { archiveFilename: part.filename } : null;
320
+ }
233
321
  const attachmentResult = await getAttachmentResult(
234
322
  message,
235
323
  desiredContent.archive
@@ -239,14 +327,18 @@ async function getFileFromArchiveFromAttachment(message, desiredContent) {
239
327
  desiredContent
240
328
  );
241
329
  }
242
- async function getFileFromAttachment(message, desiredContent) {
330
+ async function getFileFromAttachment(message, desiredContent, fetchAttachments) {
331
+ if (!fetchAttachments) {
332
+ const part = findAttachmentPart(message, desiredContent.file);
333
+ return part ? { filename: part.filename } : null;
334
+ }
243
335
  const attachmentResult = await getAttachmentResult(
244
336
  message,
245
337
  desiredContent.file
246
338
  );
247
339
  return await extractFileFromAttachment(attachmentResult, desiredContent);
248
340
  }
249
- async function getAttachmentResult(message, expression) {
341
+ function findAttachmentPart(message, expression) {
250
342
  var _a;
251
343
  const part = (_a = message.parts) == null ? void 0 : _a.find((p) => {
252
344
  return isExpressionMatch(p.filename, expression);
@@ -255,6 +347,13 @@ async function getAttachmentResult(message, expression) {
255
347
  console.info(`Attachment not found for: ${expression}`);
256
348
  return null;
257
349
  }
350
+ return part;
351
+ }
352
+ async function getAttachmentResult(message, expression) {
353
+ const part = findAttachmentPart(message, expression);
354
+ if (!part) {
355
+ return null;
356
+ }
258
357
  const { data } = await gmail.users.messages.attachments.get({
259
358
  userId: message.userId,
260
359
  messageId: message.messageId,
@@ -392,7 +491,7 @@ function isExpressionMatch(text, expression) {
392
491
  var import_language_common2 = require("@openfn/language-common");
393
492
  function getContentsFromMessages(options) {
394
493
  return async (state) => {
395
- var _a, _b;
494
+ var _a;
396
495
  const [resolvedOptions] = (0, import_util.expandReferences)(state, options);
397
496
  const defaultOptions = {
398
497
  contents: ["from", "date", "subject"],
@@ -403,11 +502,13 @@ function getContentsFromMessages(options) {
403
502
  userId: resolvedOptions.email ?? defaultOptions.userId,
404
503
  query: resolvedOptions.query,
405
504
  processedIds: resolvedOptions.processedIds,
406
- maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults
505
+ maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults,
506
+ fetchAttachments: resolvedOptions.fetchAttachments !== false
407
507
  };
408
- const contentIndicators = getContentIndicators(
508
+ const { contentIndicators, messageFormat } = resolveContentPlan(
409
509
  defaultOptions.contents,
410
- resolvedOptions.contents
510
+ resolvedOptions.contents,
511
+ opts.fetchAttachments
411
512
  );
412
513
  const contents = [];
413
514
  const newIds = [];
@@ -430,23 +531,15 @@ function getContentsFromMessages(options) {
430
531
  if (previousIds.includes(message.id)) {
431
532
  continue;
432
533
  }
433
- const content = {
434
- messageId: message.id
435
- };
436
- const messageResult = await getMessageResult(opts.userId, message.id);
437
- for (const contentIndicator of contentIndicators) {
438
- const messageContent = await getMessageContent(
439
- messageResult,
440
- contentIndicator
441
- );
442
- if (messageContent && content[contentIndicator.name]) {
443
- throw new Error(
444
- `Duplicate content name detected: ${contentIndicator.name}`
445
- );
446
- }
447
- content[_b = contentIndicator.name] ?? (content[_b] = messageContent);
448
- }
449
- contents.push(content);
534
+ contents.push(
535
+ await buildMessageContent(
536
+ opts.userId,
537
+ message.id,
538
+ contentIndicators,
539
+ messageFormat,
540
+ opts.fetchAttachments
541
+ )
542
+ );
450
543
  if (contents.length >= opts.maxResults) {
451
544
  break doNextPageToken;
452
545
  }
@@ -472,12 +565,45 @@ function sendMessage(message) {
472
565
  };
473
566
  };
474
567
  }
568
+ function getMessageById(messageId, options = {}) {
569
+ return async (state) => {
570
+ const [resolvedMessageId, resolvedOptions] = (0, import_util.expandReferences)(
571
+ state,
572
+ messageId,
573
+ options
574
+ );
575
+ if (typeof resolvedMessageId !== "string" || !resolvedMessageId) {
576
+ throw new Error("getMessageById: messageId must be a non-empty string");
577
+ }
578
+ const defaultOptions = {
579
+ contents: ["from", "date", "subject"],
580
+ userId: "me"
581
+ };
582
+ const userId = resolvedOptions.email ?? defaultOptions.userId;
583
+ const fetchAttachments = resolvedOptions.fetchAttachments !== false;
584
+ const { contentIndicators, messageFormat } = resolveContentPlan(
585
+ defaultOptions.contents,
586
+ resolvedOptions.contents,
587
+ fetchAttachments
588
+ );
589
+ const content = await buildMessageContent(
590
+ userId,
591
+ resolvedMessageId,
592
+ contentIndicators,
593
+ messageFormat,
594
+ fetchAttachments
595
+ );
596
+ return (0, import_language_common.composeNextState)(state, content);
597
+ };
598
+ }
475
599
  function execute(...operations) {
476
600
  const initialState = {
477
601
  references: [],
478
602
  data: null
479
603
  };
480
604
  return (state) => {
605
+ var _a, _b;
606
+ const isServiceAccount = ((_a = state.configuration) == null ? void 0 : _a.private_key) && ((_b = state.configuration) == null ? void 0 : _b.client_email);
481
607
  return (0, import_language_common.execute)(
482
608
  createConnection,
483
609
  ...operations,
@@ -485,7 +611,7 @@ function execute(...operations) {
485
611
  )({
486
612
  ...initialState,
487
613
  ...state,
488
- configuration: (0, import_util.normalizeOauthConfig)(state.configuration)
614
+ configuration: isServiceAccount ? state.configuration : (0, import_util.normalizeOauthConfig)(state.configuration)
489
615
  });
490
616
  };
491
617
  }
@@ -506,6 +632,7 @@ var src_default = Adaptor_exports;
506
632
  fn,
507
633
  fnIf,
508
634
  getContentsFromMessages,
635
+ getMessageById,
509
636
  lastReferenceValue,
510
637
  log,
511
638
  merge,
package/dist/index.js CHANGED
@@ -19,6 +19,7 @@ __export(Adaptor_exports, {
19
19
  fn: () => fn,
20
20
  fnIf: () => fnIf,
21
21
  getContentsFromMessages: () => getContentsFromMessages,
22
+ getMessageById: () => getMessageById,
22
23
  lastReferenceValue: () => lastReferenceValue,
23
24
  log: () => log,
24
25
  merge: () => merge,
@@ -56,19 +57,26 @@ async function getMessagesResult(userId, query, pageToken) {
56
57
  throw new Error("Error fetching messages: " + error.message);
57
58
  }
58
59
  }
59
- async function getMessageResult(userId, messageId) {
60
+ async function getMessageResult(userId, messageId, format = "full") {
60
61
  var _a, _b;
61
- const { data } = await gmail.users.messages.get({
62
- userId,
63
- id: messageId,
64
- format: "full"
65
- });
66
- return {
67
- userId,
68
- messageId,
69
- parts: (_a = data == null ? void 0 : data.payload) == null ? void 0 : _a.parts,
70
- headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
71
- };
62
+ try {
63
+ const { data } = await gmail.users.messages.get({
64
+ userId,
65
+ id: messageId,
66
+ format,
67
+ ...format === "metadata" && {
68
+ metadataHeaders: ["From", "Date", "Subject"]
69
+ }
70
+ });
71
+ return {
72
+ userId,
73
+ messageId,
74
+ parts: (_a = data == null ? void 0 : data.payload) == null ? void 0 : _a.parts,
75
+ headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
76
+ };
77
+ } catch (error) {
78
+ throw new Error(`Error fetching message ${messageId}: ` + error.message);
79
+ }
72
80
  }
73
81
  function getContentIndicators(defaultContentRequests = [], contentRequests = []) {
74
82
  const contentIndicators = contentRequests.map(getContentIndicator);
@@ -96,12 +104,20 @@ function getContentIndicator(contentRequest) {
96
104
  }
97
105
  return contentIndicator;
98
106
  }
99
- async function getMessageContent(message, desiredContent) {
107
+ async function getMessageContent(message, desiredContent, fetchAttachments = true) {
100
108
  switch (desiredContent.type) {
101
109
  case "archive":
102
- return await getFileFromArchiveFromAttachment(message, desiredContent);
110
+ return await getFileFromArchiveFromAttachment(
111
+ message,
112
+ desiredContent,
113
+ fetchAttachments
114
+ );
103
115
  case "file":
104
- return await getFileFromAttachment(message, desiredContent);
116
+ return await getFileFromAttachment(
117
+ message,
118
+ desiredContent,
119
+ fetchAttachments
120
+ );
105
121
  case "body":
106
122
  return getBodyFromMessage(message, desiredContent);
107
123
  case "from":
@@ -112,6 +128,50 @@ async function getMessageContent(message, desiredContent) {
112
128
  return `Unsupported content type: ${desiredContent.type}`;
113
129
  }
114
130
  }
131
+ function resolveContentPlan(defaultContents, requestedContents, fetchAttachments) {
132
+ const contentIndicators = getContentIndicators(
133
+ defaultContents,
134
+ requestedContents
135
+ );
136
+ const needsFullFormat = contentIndicators.some(
137
+ ({ type }) => type === "body" || type === "file" || type === "archive"
138
+ );
139
+ const messageFormat = needsFullFormat ? "full" : "metadata";
140
+ if (!fetchAttachments) {
141
+ const skippedNames = contentIndicators.filter(({ type }) => type === "file" || type === "archive").map(({ name }) => name);
142
+ if (skippedNames.length) {
143
+ console.log(
144
+ `fetchAttachments is false: skipping attachment downloads for ${skippedNames.join(
145
+ ", "
146
+ )}; matched filenames will still be included in the output`
147
+ );
148
+ }
149
+ }
150
+ return { contentIndicators, messageFormat };
151
+ }
152
+ async function buildMessageContent(userId, messageId, contentIndicators, messageFormat, fetchAttachments) {
153
+ var _a;
154
+ const content = { messageId };
155
+ const messageResult = await getMessageResult(
156
+ userId,
157
+ messageId,
158
+ messageFormat
159
+ );
160
+ for (const contentIndicator of contentIndicators) {
161
+ const messageContent = await getMessageContent(
162
+ messageResult,
163
+ contentIndicator,
164
+ fetchAttachments
165
+ );
166
+ if (messageContent && content[contentIndicator.name]) {
167
+ throw new Error(
168
+ `Duplicate content name detected: ${contentIndicator.name}`
169
+ );
170
+ }
171
+ content[_a = contentIndicator.name] ?? (content[_a] = messageContent);
172
+ }
173
+ return content;
174
+ }
115
175
  async function buildAndSendMessage(message) {
116
176
  const attachments = await parseAttachments(message.attachments);
117
177
  const hasAttachments = attachments && attachments.length > 0;
@@ -181,10 +241,33 @@ async function parseArchiveAttachment(attachment) {
181
241
  content
182
242
  };
183
243
  }
184
- function createConnection(state) {
185
- const { access_token } = state.configuration;
186
- const auth = new google.auth.OAuth2();
187
- auth.credentials = { access_token };
244
+ async function createConnection(state) {
245
+ const {
246
+ access_token,
247
+ private_key,
248
+ client_email,
249
+ subject,
250
+ scopes = []
251
+ } = state.configuration;
252
+ const mandatoryScopes = [
253
+ "https://mail.google.com/",
254
+ "https://www.googleapis.com/auth/userinfo.email",
255
+ "https://www.googleapis.com/auth/userinfo.profile",
256
+ "openid"
257
+ ];
258
+ let auth;
259
+ if (private_key && client_email) {
260
+ auth = new google.auth.JWT({
261
+ email: client_email,
262
+ key: private_key,
263
+ scopes: [...mandatoryScopes, ...scopes],
264
+ subject
265
+ });
266
+ await auth.authorize();
267
+ } else {
268
+ auth = new google.auth.OAuth2();
269
+ auth.credentials = { access_token };
270
+ }
188
271
  gmail = google.gmail({ version: "v1", auth });
189
272
  return state;
190
273
  }
@@ -192,7 +275,11 @@ function removeConnection(state) {
192
275
  gmail = void 0;
193
276
  return state;
194
277
  }
195
- async function getFileFromArchiveFromAttachment(message, desiredContent) {
278
+ async function getFileFromArchiveFromAttachment(message, desiredContent, fetchAttachments) {
279
+ if (!fetchAttachments) {
280
+ const part = findAttachmentPart(message, desiredContent.archive);
281
+ return part ? { archiveFilename: part.filename } : null;
282
+ }
196
283
  const attachmentResult = await getAttachmentResult(
197
284
  message,
198
285
  desiredContent.archive
@@ -202,14 +289,18 @@ async function getFileFromArchiveFromAttachment(message, desiredContent) {
202
289
  desiredContent
203
290
  );
204
291
  }
205
- async function getFileFromAttachment(message, desiredContent) {
292
+ async function getFileFromAttachment(message, desiredContent, fetchAttachments) {
293
+ if (!fetchAttachments) {
294
+ const part = findAttachmentPart(message, desiredContent.file);
295
+ return part ? { filename: part.filename } : null;
296
+ }
206
297
  const attachmentResult = await getAttachmentResult(
207
298
  message,
208
299
  desiredContent.file
209
300
  );
210
301
  return await extractFileFromAttachment(attachmentResult, desiredContent);
211
302
  }
212
- async function getAttachmentResult(message, expression) {
303
+ function findAttachmentPart(message, expression) {
213
304
  var _a;
214
305
  const part = (_a = message.parts) == null ? void 0 : _a.find((p) => {
215
306
  return isExpressionMatch(p.filename, expression);
@@ -218,6 +309,13 @@ async function getAttachmentResult(message, expression) {
218
309
  console.info(`Attachment not found for: ${expression}`);
219
310
  return null;
220
311
  }
312
+ return part;
313
+ }
314
+ async function getAttachmentResult(message, expression) {
315
+ const part = findAttachmentPart(message, expression);
316
+ if (!part) {
317
+ return null;
318
+ }
221
319
  const { data } = await gmail.users.messages.attachments.get({
222
320
  userId: message.userId,
223
321
  messageId: message.messageId,
@@ -370,7 +468,7 @@ import {
370
468
  } from "@openfn/language-common";
371
469
  function getContentsFromMessages(options) {
372
470
  return async (state) => {
373
- var _a, _b;
471
+ var _a;
374
472
  const [resolvedOptions] = expandReferences(state, options);
375
473
  const defaultOptions = {
376
474
  contents: ["from", "date", "subject"],
@@ -381,11 +479,13 @@ function getContentsFromMessages(options) {
381
479
  userId: resolvedOptions.email ?? defaultOptions.userId,
382
480
  query: resolvedOptions.query,
383
481
  processedIds: resolvedOptions.processedIds,
384
- maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults
482
+ maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults,
483
+ fetchAttachments: resolvedOptions.fetchAttachments !== false
385
484
  };
386
- const contentIndicators = getContentIndicators(
485
+ const { contentIndicators, messageFormat } = resolveContentPlan(
387
486
  defaultOptions.contents,
388
- resolvedOptions.contents
487
+ resolvedOptions.contents,
488
+ opts.fetchAttachments
389
489
  );
390
490
  const contents = [];
391
491
  const newIds = [];
@@ -408,23 +508,15 @@ function getContentsFromMessages(options) {
408
508
  if (previousIds.includes(message.id)) {
409
509
  continue;
410
510
  }
411
- const content = {
412
- messageId: message.id
413
- };
414
- const messageResult = await getMessageResult(opts.userId, message.id);
415
- for (const contentIndicator of contentIndicators) {
416
- const messageContent = await getMessageContent(
417
- messageResult,
418
- contentIndicator
419
- );
420
- if (messageContent && content[contentIndicator.name]) {
421
- throw new Error(
422
- `Duplicate content name detected: ${contentIndicator.name}`
423
- );
424
- }
425
- content[_b = contentIndicator.name] ?? (content[_b] = messageContent);
426
- }
427
- contents.push(content);
511
+ contents.push(
512
+ await buildMessageContent(
513
+ opts.userId,
514
+ message.id,
515
+ contentIndicators,
516
+ messageFormat,
517
+ opts.fetchAttachments
518
+ )
519
+ );
428
520
  if (contents.length >= opts.maxResults) {
429
521
  break doNextPageToken;
430
522
  }
@@ -450,12 +542,45 @@ function sendMessage(message) {
450
542
  };
451
543
  };
452
544
  }
545
+ function getMessageById(messageId, options = {}) {
546
+ return async (state) => {
547
+ const [resolvedMessageId, resolvedOptions] = expandReferences(
548
+ state,
549
+ messageId,
550
+ options
551
+ );
552
+ if (typeof resolvedMessageId !== "string" || !resolvedMessageId) {
553
+ throw new Error("getMessageById: messageId must be a non-empty string");
554
+ }
555
+ const defaultOptions = {
556
+ contents: ["from", "date", "subject"],
557
+ userId: "me"
558
+ };
559
+ const userId = resolvedOptions.email ?? defaultOptions.userId;
560
+ const fetchAttachments = resolvedOptions.fetchAttachments !== false;
561
+ const { contentIndicators, messageFormat } = resolveContentPlan(
562
+ defaultOptions.contents,
563
+ resolvedOptions.contents,
564
+ fetchAttachments
565
+ );
566
+ const content = await buildMessageContent(
567
+ userId,
568
+ resolvedMessageId,
569
+ contentIndicators,
570
+ messageFormat,
571
+ fetchAttachments
572
+ );
573
+ return composeNextState(state, content);
574
+ };
575
+ }
453
576
  function execute(...operations) {
454
577
  const initialState = {
455
578
  references: [],
456
579
  data: null
457
580
  };
458
581
  return (state) => {
582
+ var _a, _b;
583
+ const isServiceAccount = ((_a = state.configuration) == null ? void 0 : _a.private_key) && ((_b = state.configuration) == null ? void 0 : _b.client_email);
459
584
  return commonExecute(
460
585
  createConnection,
461
586
  ...operations,
@@ -463,7 +588,7 @@ function execute(...operations) {
463
588
  )({
464
589
  ...initialState,
465
590
  ...state,
466
- configuration: normalizeOauthConfig(state.configuration)
591
+ configuration: isServiceAccount ? state.configuration : normalizeOauthConfig(state.configuration)
467
592
  });
468
593
  };
469
594
  }
@@ -484,6 +609,7 @@ export {
484
609
  fn,
485
610
  fnIf,
486
611
  getContentsFromMessages,
612
+ getMessageById,
487
613
  lastReferenceValue,
488
614
  log,
489
615
  merge,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@openfn/language-gmail",
3
3
  "label": "Gmail",
4
- "version": "3.0.0",
4
+ "version": "3.2.0",
5
5
  "badge": "Community",
6
6
  "description": "OpenFn gmail adaptor",
7
7
  "type": "module",
@@ -31,8 +31,8 @@
31
31
  "assertion-error": "2.0.0",
32
32
  "chai": "4.3.6",
33
33
  "deep-eql": "4.1.1",
34
- "mocha": "^10.8.2",
35
34
  "rimraf": "3.0.2",
35
+ "sinon": "^19.0.4",
36
36
  "undici": "^7.28.0"
37
37
  },
38
38
  "repository": {
@@ -15,18 +15,20 @@
15
15
  * @typedef {Object} Options
16
16
  * @public
17
17
  * @property {string?} [query] - Gmail search query string.
18
- * @property {Array<string|MessageContent>} [contents=['from', 'date', 'subject', 'body']]
18
+ * @property {Array<string|MessageContent>} [contents=['from', 'date', 'subject']]
19
19
  * An array of strings or MessageContent objects used to specify which parts of the message to retrieve.
20
20
  * @property {Array<string>} [processedIds] - Ignore message ids which have already been processed.
21
21
  * @property {string?} [email] - The user account to retrieve messages from. Defaults to the authenticated user.
22
22
  * @property {int?} [maxResults] - Maximum number of messages to process per request. Default is 1000.
23
+ * @property {boolean} [fetchAttachments=true] - Whether to download file and archive attachments.
24
+ * When false, matched attachments are returned as filename-only objects without content.
23
25
  */
24
26
  /**
25
27
  * Downloads contents from messages of a Gmail account.
26
28
  * @public
27
29
  * @function
28
30
  * @param {Options} options - Customized options including desired contents and query.
29
- * @state {Array} data - The returned message objects, of the form `{ messageId, contents } `
31
+ * @state {Array} data - The returned message objects, of the form `{ messageId, ...contents } `
30
32
  * @state {Array<string>} processedIds - An array of string ids processed by this request
31
33
  * @returns {Operation}
32
34
  * @example <caption>Get a message with a specific subject</caption>
@@ -45,6 +47,17 @@
45
47
  * ]
46
48
  * }
47
49
  * )
50
+ * @example <caption>Get metadata without downloading requested attachments</caption>
51
+ * getContentsFromMessages(
52
+ * {
53
+ * query: 'after:2026/07/01',
54
+ * contents: [
55
+ * 'body',
56
+ * { type: 'file', name: 'report', file: /\.xlsx$/ }
57
+ * ],
58
+ * fetchAttachments: false
59
+ * }
60
+ * )
48
61
  */
49
62
  export function getContentsFromMessages(options: Options): Operation;
50
63
  /**
@@ -75,6 +88,36 @@ export function getContentsFromMessages(options: Options): Operation;
75
88
  * })
76
89
  */
77
90
  export function sendMessage(message: SendMessageOptions | SendMessageOptions[]): Operation;
91
+ /**
92
+ * Configurable options provided to getMessageById.
93
+ * @typedef {Object} MessageIdOptions
94
+ * @public
95
+ * @property {Array<string|MessageContent>} [contents=['from', 'date', 'subject']]
96
+ * An array of strings or MessageContent objects used to specify which parts of the message to retrieve.
97
+ * @property {string?} [email] - The user account to retrieve messages from. Defaults to the authenticated user.
98
+ * @property {boolean} [fetchAttachments=true] - Whether to download file and archive attachments.
99
+ * When false, matched attachments are returned as filename-only objects without content.
100
+ */
101
+ /**
102
+ * Downloads contents from a single message of a Gmail account, identified by
103
+ * its Gmail API message id.
104
+ * @public
105
+ * @function
106
+ * @param {string} messageId - Gmail API message id to fetch.
107
+ * @param {MessageIdOptions} [options] - Customized options including desired contents.
108
+ * @state {Object} data - The returned message object, of the form `{ messageId, ...contents } `
109
+ * @returns {Operation}
110
+ * @example <caption>Download attachments for a specific message identified by an earlier step</caption>
111
+ * getMessageById(
112
+ * $.data.messageId,
113
+ * {
114
+ * contents: [
115
+ * { type: 'file', name: 'report', file: /\.xlsx$/ }
116
+ * ]
117
+ * }
118
+ * )
119
+ */
120
+ export function getMessageById(messageId: string, options?: MessageIdOptions): Operation;
78
121
  /**
79
122
  * Execute a sequence of operations.
80
123
  * Wraps `language-common/execute`, and prepends initial state for http.
@@ -115,4 +158,8 @@ export type SendMessageOptions = {
115
158
  content: string | Buffer;
116
159
  }>;
117
160
  };
161
+ /**
162
+ * Configurable options provided to getMessageById.
163
+ */
164
+ export type MessageIdOptions = any;
118
165
  export { alterState, combine, cursor, dataPath, dataValue, each, field, fields, fn, fnIf, lastReferenceValue, log, merge, sourceValue } from "@openfn/language-common";
package/types/Utils.d.ts CHANGED
@@ -2,14 +2,21 @@ export function getMessagesResult(userId: any, query: any, pageToken: any): Prom
2
2
  messages: any;
3
3
  nextPageToken: any;
4
4
  }>;
5
- export function getMessageResult(userId: any, messageId: any): Promise<{
5
+ export function getMessageResult(userId: any, messageId: any, format?: string): Promise<{
6
6
  userId: any;
7
7
  messageId: any;
8
8
  parts: any;
9
9
  headers: any;
10
10
  }>;
11
11
  export function getContentIndicators(defaultContentRequests?: any[], contentRequests?: any[]): any[];
12
- export function getMessageContent(message: any, desiredContent: any): Promise<any>;
12
+ export function getMessageContent(message: any, desiredContent: any, fetchAttachments?: boolean): Promise<any>;
13
+ export function resolveContentPlan(defaultContents: any, requestedContents: any, fetchAttachments: any): {
14
+ contentIndicators: any[];
15
+ messageFormat: string;
16
+ };
17
+ export function buildMessageContent(userId: any, messageId: any, contentIndicators: any, messageFormat: any, fetchAttachments: any): Promise<{
18
+ messageId: any;
19
+ }>;
13
20
  export function buildAndSendMessage(message: any): Promise<any>;
14
- export function createConnection(state: any): any;
21
+ export function createConnection(state: any): Promise<any>;
15
22
  export function removeConnection(state: any): any;