Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

7417 workflows i can send emails using the email account #7431

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 0 additions & 29 deletions packages/twenty-emails/src/emails/workflow-action.email.tsx

This file was deleted.

1 change: 0 additions & 1 deletion packages/twenty-emails/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,3 @@ export * from './emails/delete-inactive-workspaces.email';
export * from './emails/password-reset-link.email';
export * from './emails/password-update-notify.email';
export * from './emails/send-invite-link.email';
export * from './emails/workflow-action.email';
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export class GoogleAPIsOauthCommonStrategy extends PassportStrategy(
'email',
'profile',
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/gmail.send',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we will need to put that behind a feature flag as we will need to go through the google approval process and it can take up to a month. We will be able to test with a short list of accounts in the meantime and will need the flag :)

Also it's likely that we will need to have a process to ask users to reconnect their account if we detect that the scope is missing (maybe when we try to send an email and get a 403 the first time) We already have similar mechanism for messaging sync

'https://www.googleapis.com/auth/calendar.events',
'https://www.googleapis.com/auth/profile.emails.read',
];
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { CustomException } from 'src/utils/custom-exception';

export class MailSenderException extends CustomException {
code: MailSenderExceptionCode;
martmull marked this conversation as resolved.
Show resolved Hide resolved
constructor(message: string, code: MailSenderExceptionCode) {
super(message, code);
}
}

export enum MailSenderExceptionCode {
PROVIDER_NOT_SUPPORTED = 'PROVIDER_NOT_SUPPORTED',
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,64 @@ import { Injectable, Logger } from '@nestjs/common';

import { z } from 'zod';
import Handlebars from 'handlebars';
import { JSDOM } from 'jsdom';
import DOMPurify from 'dompurify';
import { WorkflowActionEmail } from 'twenty-emails';
import { render } from '@react-email/components';

import { WorkflowActionResult } from 'src/modules/workflow/workflow-executor/types/workflow-action-result.type';
import { WorkflowSendEmailStep } from 'src/modules/workflow/workflow-executor/types/workflow-action.type';
import { EnvironmentService } from 'src/engine/core-modules/environment/environment.service';
import { EmailService } from 'src/engine/core-modules/email/email.service';
import { InjectObjectMetadataRepository } from 'src/engine/object-metadata-repository/object-metadata-repository.decorator';
import { ConnectedAccountWorkspaceEntity } from 'src/modules/connected-account/standard-objects/connected-account.workspace-entity';
import { ConnectedAccountRepository } from 'src/modules/connected-account/repositories/connected-account.repository';
import {
WorkflowStepExecutorException,
WorkflowStepExecutorExceptionCode,
} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
import { ScopedWorkspaceContextFactory } from 'src/engine/twenty-orm/factories/scoped-workspace-context.factory';
import {
MailSenderException,
MailSenderExceptionCode,
} from 'src/modules/mail-sender/exceptions/mail-sender.exception';
import { GmailClientProvider } from 'src/modules/messaging/message-import-manager/drivers/gmail/providers/gmail-client.provider';

@Injectable()
export class SendEmailWorkflowAction {
private readonly logger = new Logger(SendEmailWorkflowAction.name);
constructor(
private readonly environmentService: EnvironmentService,
private readonly emailService: EmailService,
private readonly gmailClientProvider: GmailClientProvider,
private readonly scopedWorkspaceContextFactory: ScopedWorkspaceContextFactory,
@InjectObjectMetadataRepository(ConnectedAccountWorkspaceEntity)
private readonly connectedAccountRepository: ConnectedAccountRepository,
) {}

private async getEmailClient(step: WorkflowSendEmailStep) {
const { workspaceId } = this.scopedWorkspaceContextFactory.create();

if (!workspaceId) {
throw new WorkflowStepExecutorException(
'Scoped workspace not found',
WorkflowStepExecutorExceptionCode.SCOPED_WORKSPACE_NOT_FOUND,
);
}

const connectedAccount =
await this.connectedAccountRepository.getByIdOrFail(
martmull marked this conversation as resolved.
Show resolved Hide resolved
step.settings.connectedAccountId,
workspaceId,
);

switch (connectedAccount.provider) {
case 'google':
return await this.gmailClientProvider.getGmailClient(connectedAccount);
default:
throw new MailSenderException(
`Provider ${connectedAccount.provider} is not supported`,
MailSenderExceptionCode.PROVIDER_NOT_SUPPORTED,
);
}
}

async execute({
step,
payload,
Expand All @@ -30,6 +70,8 @@ export class SendEmailWorkflowAction {
[key: string]: string;
};
}): Promise<WorkflowActionResult> {
const emailProvider = await this.getEmailClient(step);

try {
const emailSchema = z.string().trim().email('Invalid email');

Expand All @@ -43,30 +85,22 @@ export class SendEmailWorkflowAction {

const mainText = Handlebars.compile(step.settings.template)(payload);

const window = new JSDOM('').window;
const purify = DOMPurify(window);
const safeHTML = purify.sanitize(mainText || '');
const message = [
`To: ${payload.email}`,
`Subject: ${step.settings.subject || ''}`,
'MIME-Version: 1.0',
'Content-Type: text/plain; charset="UTF-8"',
'',
mainText,
].join('\n');

const email = WorkflowActionEmail({
dangerousHTML: safeHTML,
title: step.settings.title,
callToAction: step.settings.callToAction,
});
const html = render(email, {
pretty: true,
});
const text = render(email, {
plainText: true,
});
const encodedMessage = Buffer.from(message).toString('base64');

await this.emailService.send({
from: `${this.environmentService.get(
'EMAIL_FROM_NAME',
)} <${this.environmentService.get('EMAIL_FROM_ADDRESS')}>`,
to: payload.email,
subject: step.settings.subject || '',
text,
html,
await emailProvider.users.messages.send({
userId: 'me',
requestBody: {
raw: encodedMessage,
},
});

return { result: { success: true } };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ import { MessageParticipantManagerModule } from 'src/modules/messaging/message-p
GmailGetMessageListService,
GmailHandleErrorService,
],
exports: [GmailGetMessagesService, GmailGetMessageListService],
exports: [
GmailGetMessagesService,
GmailGetMessageListService,
GmailClientProvider,
],
})
export class MessagingGmailDriverModule {}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export type WorkflowCodeStepSettings = BaseWorkflowStepSettings & {
};

export type WorkflowSendEmailStepSettings = BaseWorkflowStepSettings & {
connectedAccountId: string;
subject?: string;
template?: string;
title?: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,14 @@ import { CodeWorkflowAction } from 'src/modules/serverless/workflow-actions/code
import { SendEmailWorkflowAction } from 'src/modules/mail-sender/workflow-actions/send-email.workflow-action';
import { ServerlessFunctionModule } from 'src/engine/metadata-modules/serverless-function/serverless-function.module';
import { ScopedWorkspaceContextFactory } from 'src/engine/twenty-orm/factories/scoped-workspace-context.factory';
import { MessagingGmailDriverModule } from 'src/modules/messaging/message-import-manager/drivers/gmail/messaging-gmail-driver.module';

@Module({
imports: [WorkflowCommonModule, ServerlessFunctionModule],
imports: [
WorkflowCommonModule,
ServerlessFunctionModule,
MessagingGmailDriverModule,
],
providers: [
WorkflowExecutorWorkspaceService,
ScopedWorkspaceContextFactory,
Expand Down
Loading