feat(gmail): overhaul Gmail node + create gmail trigger (#3734)

This commit is contained in:
Michael Kret
2022-09-08 15:44:34 +03:00
committed by GitHub
parent ca8c2d6577
commit 74304db4e2
24 changed files with 3858 additions and 927 deletions

View File

@@ -0,0 +1,277 @@
import { INodeProperties } from 'n8n-workflow';
export const draftOperations: INodeProperties[] = [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
noDataExpression: true,
displayOptions: {
show: {
resource: ['draft'],
},
},
options: [
{
name: 'Create',
value: 'create',
action: 'Create a draft',
},
{
name: 'Delete',
value: 'delete',
action: 'Delete a draft',
},
{
name: 'Get',
value: 'get',
action: 'Get a draft',
},
{
name: 'Get Many',
value: 'getAll',
action: 'Get all drafts',
},
],
default: 'create',
},
];
export const draftFields: INodeProperties[] = [
{
displayName: 'Draft ID',
name: 'messageId',
type: 'string',
default: '',
required: true,
displayOptions: {
show: {
resource: ['draft'],
operation: ['delete', 'get'],
},
},
placeholder: 'r-3254521568507167962',
},
{
displayName: 'Subject',
name: 'subject',
type: 'string',
default: '',
required: true,
displayOptions: {
show: {
resource: ['draft'],
operation: ['create'],
},
},
placeholder: 'Hello World!',
},
{
displayName: 'Email Type',
name: 'emailType',
type: 'options',
default: 'text',
required: true,
noDataExpression: true,
options: [
{
name: 'HTML',
value: 'html',
},
{
name: 'Text',
value: 'text',
},
],
displayOptions: {
show: {
resource: ['draft'],
operation: ['create'],
},
},
},
{
displayName: 'Message',
name: 'message',
type: 'string',
default: '',
required: true,
displayOptions: {
show: {
resource: ['draft'],
operation: ['create'],
},
},
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
displayOptions: {
show: {
resource: ['draft'],
operation: ['create'],
},
},
default: {},
options: [
{
displayName: 'To Email',
name: 'sendTo',
type: 'string',
default: '',
placeholder: 'info@example.com',
description:
'The email addresses of the recipients. Multiple addresses can be separated by a comma. e.g. jay@getsby.com, jon@smith.com.',
},
{
displayName: 'BCC',
name: 'bccList',
type: 'string',
description:
'The email addresses of the blind copy recipients. Multiple addresses can be separated by a comma. e.g. jay@getsby.com, jon@smith.com.',
placeholder: 'info@example.com',
default: '',
},
{
displayName: 'CC',
name: 'ccList',
type: 'string',
description:
'The email addresses of the copy recipients. Multiple addresses can be separated by a comma. e.g. jay@getsby.com, jon@smith.com.',
placeholder: 'info@example.com',
default: '',
},
{
displayName: 'Attachments',
name: 'attachmentsUi',
placeholder: 'Add Attachment',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
},
options: [
{
name: 'attachmentsBinary',
displayName: 'Attachment Binary',
values: [
{
displayName: 'Attachment Field Name (in Input)',
name: 'property',
type: 'string',
default: '',
description:
'Add the field name from the input node. Multiple properties can be set separated by comma.',
},
],
},
],
default: {},
description: 'Array of supported attachments to add to the message',
},
],
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
displayOptions: {
show: {
resource: ['draft'],
operation: ['get'],
},
},
default: {},
options: [
{
displayName: 'Attachment Prefix',
name: 'dataPropertyAttachmentsPrefixName',
type: 'string',
default: 'attachment_',
description:
"Prefix for name of the binary property to which to write the attachment. An index starting with 0 will be added. So if name is 'attachment_' the first attachment is saved to 'attachment_0'.",
},
{
displayName: 'Download Attachments',
name: 'downloadAttachments',
type: 'boolean',
default: false,
description: "Whether the draft's attachments will be downloaded",
},
],
},
/* -------------------------------------------------------------------------- */
/* draft:getAll */
/* -------------------------------------------------------------------------- */
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
displayOptions: {
show: {
operation: ['getAll'],
resource: ['draft'],
},
},
default: false,
description: 'Whether to return all results or only up to a given limit',
},
{
displayName: 'Limit',
name: 'limit',
type: 'number',
displayOptions: {
show: {
operation: ['getAll'],
resource: ['draft'],
returnAll: [false],
},
},
typeOptions: {
minValue: 1,
maxValue: 500,
},
default: 50,
description: 'Max number of results to return',
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
default: {},
displayOptions: {
show: {
operation: ['getAll'],
resource: ['draft'],
},
},
options: [
{
displayName: 'Attachment Prefix',
name: 'dataPropertyAttachmentsPrefixName',
type: 'string',
default: 'attachment_',
description:
"Prefix for name of the binary property to which to write the attachments. An index starting with 0 will be added. So if name is 'attachment_' the first attachment is saved to 'attachment_0'.",
},
{
displayName: 'Download Attachments',
name: 'downloadAttachments',
type: 'boolean',
default: false,
description: "Whether the draft's attachments will be downloaded",
},
{
displayName: 'Include Spam and Trash',
name: 'includeSpamTrash',
type: 'boolean',
default: false,
description: 'Whether to include messages from SPAM and TRASH in the results',
},
],
},
];

View File

@@ -0,0 +1,812 @@
/* eslint-disable n8n-nodes-base/node-filename-against-convention */
import { IExecuteFunctions } from 'n8n-core';
import {
IBinaryKeyData,
IDataObject,
ILoadOptionsFunctions,
INodeExecutionData,
INodePropertyOptions,
INodeType,
INodeTypeBaseDescription,
INodeTypeDescription,
NodeOperationError,
} from 'n8n-workflow';
import {
encodeEmail,
googleApiRequest,
googleApiRequestAllItems,
IEmail,
parseRawEmail,
prepareEmailAttachments,
prepareEmailBody,
prepareEmailsInput,
prepareQuery,
replayToEmail,
simplifyOutput,
unescapeSnippets,
} from '../GenericFunctions';
import { messageFields, messageOperations } from './MessageDescription';
import { labelFields, labelOperations } from './LabelDescription';
import { draftFields, draftOperations } from './DraftDescription';
import { threadFields, threadOperations } from './ThreadDescription';
const versionDescription: INodeTypeDescription = {
displayName: 'Gmail',
name: 'gmail',
icon: 'file:gmail.svg',
group: ['transform'],
version: 2,
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
description: 'Consume the Gmail API',
defaults: {
name: 'Gmail',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'googleApi',
required: true,
displayOptions: {
show: {
authentication: ['serviceAccount'],
},
},
},
{
name: 'gmailOAuth2',
required: true,
displayOptions: {
show: {
authentication: ['oAuth2'],
},
},
},
],
properties: [
{
displayName: 'Authentication',
name: 'authentication',
type: 'options',
options: [
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'OAuth2 (recommended)',
value: 'oAuth2',
},
{
name: 'Service Account',
value: 'serviceAccount',
},
],
default: 'oAuth2',
},
{
displayName: 'Resource',
name: 'resource',
type: 'options',
noDataExpression: true,
options: [
{
name: 'Message',
value: 'message',
},
{
name: 'Label',
value: 'label',
},
{
name: 'Draft',
value: 'draft',
},
{
name: 'Thread',
value: 'thread',
},
],
default: 'message',
},
//-------------------------------
// Draft Operations
//-------------------------------
...draftOperations,
...draftFields,
//-------------------------------
// Label Operations
//-------------------------------
...labelOperations,
...labelFields,
//-------------------------------
// Message Operations
//-------------------------------
...messageOperations,
...messageFields,
//-------------------------------
// Thread Operations
//-------------------------------
...threadOperations,
...threadFields,
//-------------------------------
],
};
export class GmailV2 implements INodeType {
description: INodeTypeDescription;
constructor(baseDescription: INodeTypeBaseDescription) {
this.description = {
...baseDescription,
...versionDescription,
};
}
methods = {
loadOptions: {
// Get all the labels to display them to user so that he can
// select them easily
async getLabels(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const labels = await googleApiRequestAllItems.call(
this,
'labels',
'GET',
'/gmail/v1/users/me/labels',
);
for (const label of labels) {
returnData.push({
name: label.name,
value: label.id,
});
}
return returnData.sort((a, b) => {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});
},
async getThreadMessages(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const id = this.getNodeParameter('threadId', 0) as string;
const { messages } = await googleApiRequest.call(
this,
'GET',
`/gmail/v1/users/me/threads/${id}`,
{},
{ format: 'minimal' },
);
for (const message of messages || []) {
returnData.push({
name: message.snippet,
value: message.id,
});
}
return returnData;
},
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: INodeExecutionData[] = [];
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;
let responseData;
for (let i = 0; i < items.length; i++) {
try {
//------------------------------------------------------------------//
// labels //
//------------------------------------------------------------------//
if (resource === 'label') {
if (operation === 'create') {
//https://developers.google.com/gmail/api/v1/reference/users/labels/create
const labelName = this.getNodeParameter('name', i) as string;
const labelListVisibility = this.getNodeParameter(
'options.labelListVisibility',
i,
'labelShow',
) as string;
const messageListVisibility = this.getNodeParameter(
'options.messageListVisibility',
i,
'show',
) as string;
const body = {
labelListVisibility,
messageListVisibility,
name: labelName,
};
responseData = await googleApiRequest.call(
this,
'POST',
'/gmail/v1/users/me/labels',
body,
);
}
if (operation === 'delete') {
//https://developers.google.com/gmail/api/v1/reference/users/labels/delete
const labelId = this.getNodeParameter('labelId', i) as string[];
const endpoint = `/gmail/v1/users/me/labels/${labelId}`;
responseData = await googleApiRequest.call(this, 'DELETE', endpoint);
responseData = { success: true };
}
if (operation === 'get') {
// https://developers.google.com/gmail/api/v1/reference/users/labels/get
const labelId = this.getNodeParameter('labelId', i);
const endpoint = `/gmail/v1/users/me/labels/${labelId}`;
responseData = await googleApiRequest.call(this, 'GET', endpoint);
}
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
responseData = await googleApiRequest.call(this, 'GET', `/gmail/v1/users/me/labels`);
responseData = this.helpers.returnJsonArray(responseData.labels);
if (!returnAll) {
const limit = this.getNodeParameter('limit', i) as number;
responseData = responseData.splice(0, limit);
}
}
}
//------------------------------------------------------------------//
// messages //
//------------------------------------------------------------------//
if (resource === 'message') {
if (operation === 'send') {
// https://developers.google.com/gmail/api/v1/reference/users/messages/send
const options = this.getNodeParameter('options', i) as IDataObject;
const sendTo = this.getNodeParameter('sendTo', i) as string;
let qs: IDataObject = {};
const to = prepareEmailsInput.call(this, sendTo, 'To', i);
let cc = '';
let bcc = '';
if (options.ccList) {
cc = prepareEmailsInput.call(this, options.ccList as string, 'CC', i);
}
if (options.bccList) {
bcc = prepareEmailsInput.call(this, options.bccList as string, 'BCC', i);
}
let attachments: IDataObject[] = [];
if (options.attachmentsUi) {
attachments = await prepareEmailAttachments.call(
this,
options.attachmentsUi as IDataObject,
items,
i,
);
if (attachments.length) {
qs = {
userId: 'me',
uploadType: 'media',
};
}
}
let from = '';
if (options.senderName) {
const { emailAddress } = await googleApiRequest.call(
this,
'GET',
'/gmail/v1/users/me/profile',
);
from = `${options.senderName as string} <${emailAddress}>`;
}
const email: IEmail = {
from,
to,
cc,
bcc,
subject: this.getNodeParameter('subject', i) as string,
...prepareEmailBody.call(this, i),
attachments,
};
const endpoint = '/gmail/v1/users/me/messages/send';
const body = {
raw: await encodeEmail(email),
};
responseData = await googleApiRequest.call(this, 'POST', endpoint, body, qs);
}
if (operation === 'reply') {
const messageIdGmail = this.getNodeParameter('messageId', i) as string;
const options = this.getNodeParameter('options', i) as IDataObject;
responseData = await replayToEmail.call(this, items, messageIdGmail, options, i);
}
if (operation === 'get') {
//https://developers.google.com/gmail/api/v1/reference/users/messages/get
const id = this.getNodeParameter('messageId', i);
const endpoint = `/gmail/v1/users/me/messages/${id}`;
const qs: IDataObject = {};
const options = this.getNodeParameter('options', i, {}) as IDataObject;
const simple = this.getNodeParameter('simple', i) as boolean;
if (simple) {
qs.format = 'metadata';
qs.metadataHeaders = ['From', 'To', 'Cc', 'Bcc', 'Subject'];
} else {
qs.format = 'raw';
}
responseData = await googleApiRequest.call(this, 'GET', endpoint, {}, qs);
let nodeExecutionData: INodeExecutionData;
if (!simple) {
const dataPropertyNameDownload =
(options.dataPropertyAttachmentsPrefixName as string) || 'attachment_';
nodeExecutionData = await parseRawEmail.call(
this,
responseData,
dataPropertyNameDownload,
);
} else {
const [json, _] = await simplifyOutput.call(this, [responseData]);
nodeExecutionData = { json };
}
responseData = [nodeExecutionData];
}
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const options = this.getNodeParameter('options', i, {}) as IDataObject;
const filters = this.getNodeParameter('filters', i, {}) as IDataObject;
const qs: IDataObject = {};
Object.assign(qs, prepareQuery.call(this, filters), options);
if (returnAll) {
responseData = await googleApiRequestAllItems.call(
this,
'messages',
'GET',
`/gmail/v1/users/me/messages`,
{},
qs,
);
} else {
qs.maxResults = this.getNodeParameter('limit', i) as number;
responseData = await googleApiRequest.call(
this,
'GET',
`/gmail/v1/users/me/messages`,
{},
qs,
);
responseData = responseData.messages;
}
if (responseData === undefined) {
responseData = [];
}
const simple = this.getNodeParameter('simple', i) as boolean;
if (simple) {
qs.format = 'metadata';
qs.metadataHeaders = ['From', 'To', 'Cc', 'Bcc', 'Subject'];
} else {
qs.format = 'raw';
}
for (let i = 0; i < responseData.length; i++) {
responseData[i] = await googleApiRequest.call(
this,
'GET',
`/gmail/v1/users/me/messages/${responseData[i].id}`,
{},
qs,
);
if (!simple) {
const dataPropertyNameDownload =
(options.dataPropertyAttachmentsPrefixName as string) || 'attachment_';
responseData[i] = await parseRawEmail.call(
this,
responseData[i],
dataPropertyNameDownload,
);
}
}
if (simple) {
responseData = this.helpers.returnJsonArray(
await simplifyOutput.call(this, responseData),
);
}
}
if (operation === 'delete') {
// https://developers.google.com/gmail/api/v1/reference/users/messages/delete
const id = this.getNodeParameter('messageId', i);
const endpoint = `/gmail/v1/users/me/messages/${id}`;
responseData = await googleApiRequest.call(this, 'DELETE', endpoint);
responseData = { success: true };
}
if (operation === 'markAsRead') {
// https://developers.google.com/gmail/api/reference/rest/v1/users.messages/modify
const id = this.getNodeParameter('messageId', i);
const endpoint = `/gmail/v1/users/me/messages/${id}/modify`;
const body = {
removeLabelIds: ['UNREAD'],
};
responseData = await googleApiRequest.call(this, 'POST', endpoint, body);
}
if (operation === 'markAsUnread') {
// https://developers.google.com/gmail/api/reference/rest/v1/users.messages/modify
const id = this.getNodeParameter('messageId', i);
const endpoint = `/gmail/v1/users/me/messages/${id}/modify`;
const body = {
addLabelIds: ['UNREAD'],
};
responseData = await googleApiRequest.call(this, 'POST', endpoint, body);
}
if (operation === 'addLabels') {
const id = this.getNodeParameter('messageId', i);
const labelIds = this.getNodeParameter('labelIds', i) as string[];
const endpoint = `/gmail/v1/users/me/messages/${id}/modify`;
const body = {
addLabelIds: labelIds,
};
responseData = await googleApiRequest.call(this, 'POST', endpoint, body);
}
if (operation === 'removeLabels') {
const id = this.getNodeParameter('messageId', i);
const labelIds = this.getNodeParameter('labelIds', i) as string[];
const endpoint = `/gmail/v1/users/me/messages/${id}/modify`;
const body = {
removeLabelIds: labelIds,
};
responseData = await googleApiRequest.call(this, 'POST', endpoint, body);
}
}
//------------------------------------------------------------------//
// drafts //
//------------------------------------------------------------------//
if (resource === 'draft') {
if (operation === 'create') {
// https://developers.google.com/gmail/api/v1/reference/users/drafts/create
const options = this.getNodeParameter('options', i) as IDataObject;
let qs: IDataObject = {};
let to = '';
let cc = '';
let bcc = '';
if (options.sendTo) {
to += prepareEmailsInput.call(this, options.sendTo as string, 'To', i);
}
if (options.ccList) {
cc = prepareEmailsInput.call(this, options.ccList as string, 'CC', i);
}
if (options.bccList) {
bcc = prepareEmailsInput.call(this, options.bccList as string, 'BCC', i);
}
let attachments: IDataObject[] = [];
if (options.attachmentsUi) {
attachments = await prepareEmailAttachments.call(
this,
options.attachmentsUi as IDataObject,
items,
i,
);
if (attachments.length) {
qs = {
userId: 'me',
uploadType: 'media',
};
}
}
const email: IEmail = {
to,
cc,
bcc,
subject: this.getNodeParameter('subject', i) as string,
...prepareEmailBody.call(this, i),
attachments,
};
const body = {
message: {
raw: await encodeEmail(email),
},
};
responseData = await googleApiRequest.call(
this,
'POST',
'/gmail/v1/users/me/drafts',
body,
qs,
);
}
if (operation === 'get') {
// https://developers.google.com/gmail/api/v1/reference/users/drafts/get
const id = this.getNodeParameter('messageId', i);
const endpoint = `/gmail/v1/users/me/drafts/${id}`;
const qs: IDataObject = {};
const options = this.getNodeParameter('options', i) as IDataObject;
qs.format = 'raw';
responseData = await googleApiRequest.call(this, 'GET', endpoint, {}, qs);
let nodeExecutionData: INodeExecutionData;
const dataPropertyNameDownload =
(options.dataPropertyAttachmentsPrefixName as string) || 'attachment_';
nodeExecutionData = await parseRawEmail.call(
this,
responseData.message,
dataPropertyNameDownload,
);
// Add the draft-id
nodeExecutionData.json.messageId = nodeExecutionData.json.id;
nodeExecutionData.json.id = responseData.id;
responseData = [nodeExecutionData];
}
if (operation === 'delete') {
// https://developers.google.com/gmail/api/v1/reference/users/drafts/delete
const id = this.getNodeParameter('messageId', i);
const endpoint = `/gmail/v1/users/me/drafts/${id}`;
responseData = await googleApiRequest.call(this, 'DELETE', endpoint);
responseData = { success: true };
}
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const options = this.getNodeParameter('options', i) as IDataObject;
const qs: IDataObject = {};
Object.assign(qs, options);
if (returnAll) {
responseData = await googleApiRequestAllItems.call(
this,
'drafts',
'GET',
`/gmail/v1/users/me/drafts`,
{},
qs,
);
} else {
qs.maxResults = this.getNodeParameter('limit', i) as number;
responseData = await googleApiRequest.call(
this,
'GET',
`/gmail/v1/users/me/drafts`,
{},
qs,
);
responseData = responseData.drafts;
}
if (responseData === undefined) {
responseData = [];
}
qs.format = 'raw';
for (let i = 0; i < responseData.length; i++) {
responseData[i] = await googleApiRequest.call(
this,
'GET',
`/gmail/v1/users/me/drafts/${responseData[i].id}`,
{},
qs,
);
const dataPropertyNameDownload =
(options.dataPropertyAttachmentsPrefixName as string) || 'attachment_';
const id = responseData[i].id;
responseData[i] = await parseRawEmail.call(
this,
responseData[i].message,
dataPropertyNameDownload,
);
// Add the draft-id
responseData[i].json.messageId = responseData[i].json.id;
responseData[i].json.id = id;
}
}
}
//------------------------------------------------------------------//
// threads //
//------------------------------------------------------------------//
if (resource === 'thread') {
if (operation === 'delete') {
//https://developers.google.com/gmail/api/reference/rest/v1/users.threads/delete
const id = this.getNodeParameter('threadId', i);
const endpoint = `/gmail/v1/users/me/threads/${id}`;
responseData = await googleApiRequest.call(this, 'DELETE', endpoint);
responseData = { success: true };
}
if (operation === 'get') {
//https://developers.google.com/gmail/api/reference/rest/v1/users.threads/get
const id = this.getNodeParameter('threadId', i);
const endpoint = `/gmail/v1/users/me/threads/${id}`;
const options = this.getNodeParameter('options', i) as IDataObject;
const onlyMessages = options.returnOnlyMessages || false;
const qs: IDataObject = {};
const simple = this.getNodeParameter('simple', i) as boolean;
if (simple) {
qs.format = 'metadata';
qs.metadataHeaders = ['From', 'To', 'Cc', 'Bcc', 'Subject'];
} else {
qs.format = 'full';
}
responseData = await googleApiRequest.call(this, 'GET', endpoint, {}, qs);
if (onlyMessages) {
responseData = this.helpers.returnJsonArray(
await simplifyOutput.call(this, responseData.messages),
);
} else {
responseData.messages = await simplifyOutput.call(this, responseData.messages);
responseData = [{ json: responseData }];
}
}
if (operation === 'getAll') {
//https://developers.google.com/gmail/api/reference/rest/v1/users.threads/list
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const filters = this.getNodeParameter('filters', i) as IDataObject;
const qs: IDataObject = {};
Object.assign(qs, prepareQuery.call(this, filters));
if (returnAll) {
responseData = await googleApiRequestAllItems.call(
this,
'threads',
'GET',
`/gmail/v1/users/me/threads`,
{},
qs,
);
} else {
qs.maxResults = this.getNodeParameter('limit', i) as number;
responseData = await googleApiRequest.call(
this,
'GET',
`/gmail/v1/users/me/threads`,
{},
qs,
);
responseData = responseData.threads;
}
if (responseData === undefined) {
responseData = [];
}
responseData = this.helpers.returnJsonArray(responseData);
}
if (operation === 'reply') {
const messageIdGmail = this.getNodeParameter('messageId', i) as string;
const options = this.getNodeParameter('options', i) as IDataObject;
responseData = await replayToEmail.call(this, items, messageIdGmail, options, i);
}
if (operation === 'trash') {
//https://developers.google.com/gmail/api/reference/rest/v1/users.threads/trash
const id = this.getNodeParameter('threadId', i);
const endpoint = `/gmail/v1/users/me/threads/${id}/trash`;
responseData = await googleApiRequest.call(this, 'POST', endpoint);
}
if (operation === 'untrash') {
//https://developers.google.com/gmail/api/reference/rest/v1/users.threads/untrash
const id = this.getNodeParameter('threadId', i);
const endpoint = `/gmail/v1/users/me/threads/${id}/untrash`;
responseData = await googleApiRequest.call(this, 'POST', endpoint);
}
if (operation === 'addLabels') {
const id = this.getNodeParameter('threadId', i);
const labelIds = this.getNodeParameter('labelIds', i) as string[];
const endpoint = `/gmail/v1/users/me/threads/${id}/modify`;
const body = {
addLabelIds: labelIds,
};
responseData = await googleApiRequest.call(this, 'POST', endpoint, body);
}
if (operation === 'removeLabels') {
const id = this.getNodeParameter('threadId', i);
const labelIds = this.getNodeParameter('labelIds', i) as string[];
const endpoint = `/gmail/v1/users/me/threads/${id}/modify`;
const body = {
removeLabelIds: labelIds,
};
responseData = await googleApiRequest.call(this, 'POST', endpoint, body);
}
}
//------------------------------------------------------------------//
const executionData = this.helpers.constructExecutionMetaData(this.helpers.returnJsonArray(responseData), {
itemData: { item: i },
});
returnData.push(...executionData);
} catch (error) {
error.message = `${error.message} (item ${i})`;
if (this.continueOnFail()) {
returnData.push({ json: { error: error.message }, pairedItem: { item: i } });
continue;
}
throw new NodeOperationError(this.getNode(), error, {
description: error.description,
itemIndex: i,
});
}
}
if (
['draft', 'message', 'thread'].includes(resource) &&
['get', 'getAll'].includes(operation)
) {
return this.prepareOutputData(unescapeSnippets(returnData));
}
return this.prepareOutputData(returnData);
}
}

View File

@@ -0,0 +1,159 @@
import { INodeProperties } from 'n8n-workflow';
export const labelOperations: INodeProperties[] = [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
noDataExpression: true,
displayOptions: {
show: {
resource: ['label'],
},
},
options: [
{
name: 'Create',
value: 'create',
action: 'Create a label',
},
{
name: 'Delete',
value: 'delete',
action: 'Delete a label',
},
{
name: 'Get',
value: 'get',
action: 'Get a label info',
},
{
name: 'Get Many',
value: 'getAll',
action: 'Get all labels',
},
],
default: 'getAll',
},
];
export const labelFields: INodeProperties[] = [
{
displayName: 'Name',
name: 'name',
type: 'string',
default: '',
required: true,
displayOptions: {
show: {
resource: ['label'],
operation: ['create'],
},
},
placeholder: 'invoices',
description: 'Label Name',
},
{
displayName: 'Label ID',
name: 'labelId',
type: 'string',
default: '',
required: true,
displayOptions: {
show: {
resource: ['label'],
operation: ['get', 'delete'],
},
},
description: 'The ID of the label',
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
displayOptions: {
show: {
resource: ['label'],
operation: ['create'],
},
},
default: {},
options: [
{
displayName: 'Label List Visibility',
name: 'labelListVisibility',
type: 'options',
options: [
{
name: 'Hide',
value: 'labelHide',
},
{
name: 'Show',
value: 'labelShow',
},
{
name: 'Show If Unread',
value: 'labelShowIfUnread',
},
],
default: 'labelShow',
description: 'The visibility of the label in the label list in the Gmail web interface',
},
{
displayName: 'Message List Visibility',
name: 'messageListVisibility',
type: 'options',
options: [
{
name: 'Hide',
value: 'hide',
},
{
name: 'Show',
value: 'show',
},
],
default: 'show',
description:
'The visibility of messages with this label in the message list in the Gmail web interface',
},
],
},
/* -------------------------------------------------------------------------- */
/* label:getAll */
/* -------------------------------------------------------------------------- */
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
displayOptions: {
show: {
operation: ['getAll'],
resource: ['label'],
},
},
default: false,
description: 'Whether to return all results or only up to a given limit',
},
{
displayName: 'Limit',
name: 'limit',
type: 'number',
displayOptions: {
show: {
operation: ['getAll'],
resource: ['label'],
returnAll: [false],
},
},
typeOptions: {
minValue: 1,
maxValue: 500,
},
default: 50,
description: 'Max number of results to return',
},
];

View File

@@ -0,0 +1,506 @@
import { INodeProperties } from 'n8n-workflow';
export const messageOperations: INodeProperties[] = [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
noDataExpression: true,
displayOptions: {
show: {
resource: ['message'],
},
},
options: [
{
name: 'Add Label',
value: 'addLabels',
action: 'Add label to message',
},
{
name: 'Delete',
value: 'delete',
action: 'Delete a message',
},
{
name: 'Get',
value: 'get',
action: 'Get a message',
},
{
name: 'Get Many',
value: 'getAll',
action: 'Get all messages',
},
{
name: 'Mark as Read',
value: 'markAsRead',
action: 'Mark a message as read',
},
{
name: 'Mark as Unread',
value: 'markAsUnread',
action: 'Mark a message as unread',
},
{
name: 'Remove Label',
value: 'removeLabels',
action: 'Remove label from message',
},
{
name: 'Reply',
value: 'reply',
action: 'Reply to a message',
},
{
name: 'Send',
value: 'send',
action: 'Send a message',
},
],
default: 'send',
},
];
export const messageFields: INodeProperties[] = [
{
displayName: 'Message ID',
name: 'messageId',
type: 'string',
default: '',
required: true,
displayOptions: {
show: {
resource: ['message'],
operation: ['get', 'delete', 'markAsRead', 'markAsUnread'],
},
},
placeholder: '172ce2c4a72cc243',
},
{
displayName: 'Message ID',
name: 'messageId',
type: 'string',
default: '',
required: true,
displayOptions: {
show: {
resource: ['message'],
operation: ['reply'],
},
},
placeholder: '172ce2c4a72cc243',
},
{
displayName: 'To',
name: 'sendTo',
type: 'string',
default: '',
required: true,
displayOptions: {
show: {
resource: ['message'],
operation: ['send'],
},
},
placeholder: 'info@example.com',
description:
'The email addresses of the recipients. Multiple addresses can be separated by a comma. e.g. jay@getsby.com, jon@smith.com.',
},
{
displayName: 'Subject',
name: 'subject',
type: 'string',
default: '',
required: true,
displayOptions: {
show: {
resource: ['message'],
operation: ['send'],
},
},
placeholder: 'Hello World!',
},
{
displayName: 'Email Type',
name: 'emailType',
type: 'options',
default: 'text',
required: true,
noDataExpression: true,
options: [
{
name: 'Text',
value: 'text',
},
{
name: 'HTML',
value: 'html',
},
],
displayOptions: {
show: {
resource: ['message'],
operation: ['send', 'reply'],
},
},
},
{
displayName: 'Message',
name: 'message',
type: 'string',
default: '',
required: true,
displayOptions: {
show: {
resource: ['message'],
operation: ['reply', 'send'],
},
},
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
displayOptions: {
show: {
resource: ['message'],
operation: ['send', 'reply'],
},
},
default: {},
options: [
{
displayName: 'Attachments',
name: 'attachmentsUi',
placeholder: 'Add Attachment',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
},
options: [
{
name: 'attachmentsBinary',
displayName: 'Attachment Binary',
values: [
{
displayName: 'Attachment Field Name',
name: 'property',
type: 'string',
default: 'data',
description:
'Add the field name from the input node. Multiple properties can be set separated by comma.',
hint: 'The name of the field with the attachment in the node input',
},
],
},
],
default: {},
description: 'Array of supported attachments to add to the message',
},
{
displayName: 'BCC',
name: 'bccList',
type: 'string',
description:
'The email addresses of the blind copy recipients. Multiple addresses can be separated by a comma. e.g. jay@getsby.com, jon@smith.com.',
placeholder: 'info@example.com',
default: '',
},
{
displayName: 'CC',
name: 'ccList',
type: 'string',
description:
'The email addresses of the copy recipients. Multiple addresses can be separated by a comma. e.g. jay@getsby.com, jon@smith.com.',
placeholder: 'info@example.com',
default: '',
},
{
displayName: 'Sender Name',
name: 'senderName',
type: 'string',
placeholder: 'e.g. Nathan',
default: '',
description: "The name that will be shown in recipients' inboxes",
},
{
displayName: 'Reply to Sender Only',
name: 'replyToSenderOnly',
type: 'boolean',
default: false,
description: 'Whether to reply to the sender only or to the entire list of recipients',
},
],
},
{
displayName: 'Simplify',
name: 'simple',
type: 'boolean',
displayOptions: {
show: {
operation: ['get'],
resource: ['message'],
},
},
default: true,
description: 'Whether to return a simplified version of the response instead of the raw data',
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
displayOptions: {
show: {
resource: ['message'],
operation: ['get'],
},
hide: {
simple: [true],
},
},
default: {},
options: [
{
displayName: 'Attachment Prefix',
name: 'dataPropertyAttachmentsPrefixName',
type: 'string',
default: 'attachment_',
description:
"Prefix for name of the binary property to which to write the attachment. An index starting with 0 will be added. So if name is 'attachment_' the first attachment is saved to 'attachment_0'.",
},
{
displayName: 'Download Attachments',
name: 'downloadAttachments',
type: 'boolean',
default: false,
description:
"Whether the email's attachments will be downloaded and included in the output",
},
],
},
/* -------------------------------------------------------------------------- */
/* message:getAll */
/* -------------------------------------------------------------------------- */
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
displayOptions: {
show: {
operation: ['getAll'],
resource: ['message'],
},
},
default: false,
description: 'Whether to return all results or only up to a given limit',
},
{
displayName: 'Limit',
name: 'limit',
type: 'number',
displayOptions: {
show: {
operation: ['getAll'],
resource: ['message'],
returnAll: [false],
},
},
typeOptions: {
minValue: 1,
maxValue: 500,
},
default: 50,
description: 'Max number of results to return',
},
{
displayName: 'Simplify',
name: 'simple',
type: 'boolean',
displayOptions: {
show: {
operation: ['getAll'],
resource: ['message'],
},
},
default: true,
description: 'Whether to return a simplified version of the response instead of the raw data',
},
{
displayName:
'Fetching a lot of messages may take a long time. Consider using filters to speed things up',
name: 'filtersNotice',
type: 'notice',
default: '',
displayOptions: {
show: {
operation: ['getAll'],
resource: ['message'],
returnAll: [true],
},
},
},
{
displayName: 'Filters',
name: 'filters',
type: 'collection',
placeholder: 'Add Filter',
default: {},
displayOptions: {
show: {
operation: ['getAll'],
resource: ['message'],
},
},
options: [
{
displayName: 'Include Spam and Trash',
name: 'includeSpamTrash',
type: 'boolean',
default: false,
description: 'Whether to include messages from SPAM and TRASH in the results',
},
{
displayName: 'Label Names or IDs',
name: 'labelIds',
type: 'multiOptions',
typeOptions: {
loadOptionsMethod: 'getLabels',
},
default: [],
description:
'Only return messages with labels that match all of the specified label IDs. Choose from the list, or specify IDs using an <a href="https://docs.n8n.io/code-examples/expressions/">expression</a>.',
},
{
displayName: 'Search',
name: 'q',
type: 'string',
default: '',
placeholder: 'has:attachment',
hint: 'Use the same format as in the Gmail search box. <a href="https://support.google.com/mail/answer/7190?hl=en">More info</a>.',
description: 'Only return messages matching the specified query',
},
{
displayName: 'Read Status',
name: 'readStatus',
type: 'options',
default: 'unread',
hint: 'Filter emails by whether they have been read or not',
options: [
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'Unread and read emails',
value: 'both',
},
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'Unread emails only',
value: 'unread',
},
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'Read emails only',
value: 'read',
},
],
},
{
displayName: 'Received After',
name: 'receivedAfter',
type: 'dateTime',
default: '',
description:
'Get all emails received after the specified date. In an expression you can set date using string in ISO format or a timestamp in miliseconds.',
},
{
displayName: 'Received Before',
name: 'receivedBefore',
type: 'dateTime',
default: '',
description:
'Get all emails received before the specified date. In an expression you can set date using string in ISO format or a timestamp in miliseconds.',
},
{
displayName: 'Sender',
name: 'sender',
type: 'string',
default: '',
description: 'Sender name or email to filter by',
hint: 'Enter an email or part of a sender name',
},
],
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
default: {},
displayOptions: {
show: {
operation: ['getAll'],
resource: ['message'],
},
hide: {
simple: [true],
},
},
options: [
{
displayName: 'Attachment Prefix',
name: 'dataPropertyAttachmentsPrefixName',
type: 'string',
default: 'attachment_',
description:
"Prefix for name of the binary property to which to write the attachment. An index starting with 0 will be added. So if name is 'attachment_' the first attachment is saved to 'attachment_0'.",
},
{
displayName: 'Download Attachments',
name: 'downloadAttachments',
type: 'boolean',
default: false,
description:
"Whether the email's attachments will be downloaded and included in the output",
},
],
},
/* -------------------------------------------------------------------------- */
/* label:addLabel, removeLabel */
/* -------------------------------------------------------------------------- */
{
displayName: 'Message ID',
name: 'messageId',
type: 'string',
default: '',
required: true,
placeholder: '172ce2c4a72cc243',
displayOptions: {
show: {
resource: ['message'],
operation: ['addLabels', 'removeLabels'],
},
},
},
{
displayName: 'Label Names or IDs',
name: 'labelIds',
type: 'multiOptions',
typeOptions: {
loadOptionsMethod: 'getLabels',
},
default: [],
required: true,
displayOptions: {
show: {
resource: ['message'],
operation: ['addLabels', 'removeLabels'],
},
},
description:
'Choose from the list, or specify IDs using an <a href="https://docs.n8n.io/code-examples/expressions/">expression</a>',
},
];

View File

@@ -0,0 +1,415 @@
import { INodeProperties } from 'n8n-workflow';
export const threadOperations: INodeProperties[] = [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
noDataExpression: true,
displayOptions: {
show: {
resource: ['thread'],
},
},
options: [
{
name: 'Add Label',
value: 'addLabels',
action: 'Add label to thread',
},
{
name: 'Delete',
value: 'delete',
action: 'Delete a thread',
},
{
name: 'Get',
value: 'get',
action: 'Get a thread',
},
{
name: 'Get Many',
value: 'getAll',
action: 'Get all threads',
},
{
name: 'Remove Label',
value: 'removeLabels',
action: 'Remove label from thread',
},
{
name: 'Reply',
value: 'reply',
action: 'Reply to a message',
},
{
name: 'Trash',
value: 'trash',
action: 'Trash a thread',
},
{
name: 'Untrash',
value: 'untrash',
action: 'Untrash a thread',
},
],
default: 'getAll',
},
];
export const threadFields: INodeProperties[] = [
{
displayName: 'Thread ID',
name: 'threadId',
type: 'string',
default: '',
required: true,
description: 'The ID of the thread you are operating on',
displayOptions: {
show: {
resource: ['thread'],
operation: ['get', 'delete', 'reply', 'trash', 'untrash'],
},
},
},
/* -------------------------------------------------------------------------- */
/* thread:reply */
/* -------------------------------------------------------------------------- */
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-wrong-for-dynamic-options
displayName: 'Message Snippet or ID',
name: 'messageId',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getThreadMessages',
loadOptionsDependsOn: ['threadId'],
},
default: '',
description:
'Choose from the list, or specify an ID using an <a href="https://docs.n8n.io/code-examples/expressions/">expression</a>',
displayOptions: {
show: {
resource: ['thread'],
operation: ['reply'],
},
},
},
{
displayName: 'Email Type',
name: 'emailType',
type: 'options',
default: 'text',
required: true,
noDataExpression: true,
options: [
{
name: 'Text',
value: 'text',
},
{
name: 'HTML',
value: 'html',
},
],
displayOptions: {
show: {
resource: ['thread'],
operation: ['reply'],
},
},
},
{
displayName: 'Message',
name: 'message',
type: 'string',
default: '',
required: true,
displayOptions: {
show: {
resource: ['thread'],
operation: ['reply'],
},
},
hint: 'Get better Text and Expressions writing experience by using the expression editor',
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
displayOptions: {
show: {
resource: ['thread'],
operation: ['reply'],
},
},
default: {},
options: [
{
displayName: 'Attachments',
name: 'attachmentsUi',
placeholder: 'Add Attachment',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
},
options: [
{
name: 'attachmentsBinary',
displayName: 'Attachment Binary',
values: [
{
displayName: 'Attachment Field Name',
name: 'property',
type: 'string',
default: '',
description:
'Add the field name from the input node. Multiple properties can be set separated by comma.',
},
],
},
],
default: {},
description: 'Array of supported attachments to add to the message',
},
{
displayName: 'BCC',
name: 'bccList',
type: 'string',
description:
'The email addresses of the blind copy recipients. Multiple addresses can be separated by a comma. e.g. jay@getsby.com, jon@smith.com.',
placeholder: 'info@example.com',
default: '',
},
{
displayName: 'CC',
name: 'ccList',
type: 'string',
description:
'The email addresses of the copy recipients. Multiple addresses can be separated by a comma. e.g. jay@getsby.com, jon@smith.com.',
placeholder: 'info@example.com',
default: '',
},
{
displayName: 'Sender Name',
name: 'senderName',
type: 'string',
placeholder: 'e.g. Nathan',
default: '',
description: 'The name displayed in your contacts inboxes',
},
{
displayName: 'Reply to Sender Only',
name: 'replyToSenderOnly',
type: 'boolean',
default: false,
description: 'Whether to reply to the sender only or to the entire list of recipients',
},
],
},
/* -------------------------------------------------------------------------- */
/* thread:get */
/* -------------------------------------------------------------------------- */
{
displayName: 'Simplify',
name: 'simple',
type: 'boolean',
displayOptions: {
show: {
operation: ['get'],
resource: ['thread'],
},
},
default: true,
description: 'Whether to return a simplified version of the response instead of the raw data',
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Field',
displayOptions: {
show: {
resource: ['thread'],
operation: ['get'],
},
},
default: {},
options: [
{
displayName: 'Return Only Messages',
name: 'returnOnlyMessages',
type: 'boolean',
default: true,
description: 'Whether to return only thread messages',
},
],
},
/* -------------------------------------------------------------------------- */
/* thread:getAll */
/* -------------------------------------------------------------------------- */
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
displayOptions: {
show: {
operation: ['getAll'],
resource: ['thread'],
},
},
default: false,
description: 'Whether to return all results or only up to a given limit',
},
{
displayName: 'Limit',
name: 'limit',
type: 'number',
displayOptions: {
show: {
operation: ['getAll'],
resource: ['thread'],
returnAll: [false],
},
},
typeOptions: {
minValue: 1,
maxValue: 500,
},
default: 50,
description: 'Max number of results to return',
},
{
displayName:
'Fetching a lot of messages may take a long time. Consider using filters to speed things up',
name: 'filtersNotice',
type: 'notice',
default: '',
displayOptions: {
show: {
operation: ['getAll'],
resource: ['thread'],
returnAll: [true],
},
},
},
{
displayName: 'Filters',
name: 'filters',
type: 'collection',
placeholder: 'Add Filter',
default: {},
displayOptions: {
show: {
operation: ['getAll'],
resource: ['thread'],
},
},
options: [
{
displayName: 'Include Spam and Trash',
name: 'includeSpamTrash',
type: 'boolean',
default: false,
description: 'Whether to include threads from SPAM and TRASH in the results',
},
{
displayName: 'Label ID Names or IDs',
name: 'labelIds',
type: 'multiOptions',
typeOptions: {
loadOptionsMethod: 'getLabels',
},
default: [],
description:
'Only return threads with labels that match all of the specified label IDs. Choose from the list, or specify IDs using an <a href="https://docs.n8n.io/code-examples/expressions/">expression</a>.',
},
{
displayName: 'Search',
name: 'q',
type: 'string',
default: '',
placeholder: 'has:attachment',
hint: 'Use the same format as in the Gmail search box. <a href="https://support.google.com/mail/answer/7190?hl=en">More info</a>.',
description: 'Only return messages matching the specified query',
},
{
displayName: 'Read Status',
name: 'readStatus',
type: 'options',
default: 'unread',
hint: 'Filter emails by whether they have been read or not',
options: [
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'Unread and read emails',
value: 'both',
},
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'Unread emails only',
value: 'unread',
},
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'Read emails only',
value: 'read',
},
],
},
{
displayName: 'Received After',
name: 'receivedAfter',
type: 'dateTime',
default: '',
description:
'Get all emails received after the specified date. In an expression you can set date using string in ISO format or a timestamp in miliseconds.',
},
{
displayName: 'Received Before',
name: 'receivedBefore',
type: 'dateTime',
default: '',
description:
'Get all emails received before the specified date. In an expression you can set date using string in ISO format or a timestamp in miliseconds.',
},
],
},
/* -------------------------------------------------------------------------- */
/* label:addLabel, removeLabel */
/* -------------------------------------------------------------------------- */
{
displayName: 'Thread ID',
name: 'threadId',
type: 'string',
default: '',
required: true,
placeholder: '172ce2c4a72cc243',
displayOptions: {
show: {
resource: ['thread'],
operation: ['addLabels', 'removeLabels'],
},
},
},
{
displayName: 'Label Names or IDs',
name: 'labelIds',
type: 'multiOptions',
typeOptions: {
loadOptionsMethod: 'getLabels',
},
default: [],
required: true,
displayOptions: {
show: {
resource: ['thread'],
operation: ['addLabels', 'removeLabels'],
},
},
description:
'Choose from the list, or specify IDs using an <a href="https://docs.n8n.io/code-examples/expressions/">expression</a>',
},
];