The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Stop selecting non-mailbox connected accounts as the email sender (#25814)
neo773c365b3c0db88
diff --git a/packages/twenty-front/src/modules/accounts/utils/canConnectedAccountSendEmail.ts b/packages/twenty-front/src/modules/accounts/utils/canConnectedAccountSendEmail.tsdeleted file mode 100644index c661b4c1c6d..00000000000--- a/packages/twenty-front/src/modules/accounts/utils/canConnectedAccountSendEmail.ts+++ /dev/null@@ -1,9 +0,0 @@-import { type ConnectedAccount } from '@/accounts/types/ConnectedAccount';-import { ConnectedAccountProvider } from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';--export const canConnectedAccountSendEmail = (- account: Pick<ConnectedAccount, 'provider' | 'connectionParameters'>,-): boolean =>- account.provider !== ConnectedAccountProvider.IMAP_SMTP_CALDAV ||- isDefined(account.connectionParameters?.SMTP);diff --git a/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx b/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsxindex f4337cbd765..f7e059fcb4e 100644--- a/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx+++ b/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx@@ -1,9 +1,14 @@+import { EmailOperation } from 'twenty-shared/types';import { useQuery } from '@apollo/client/react';import { useContext } from 'react';import { DragDropProvider } from '@dnd-kit/react';import { styled } from '@linaria/react';import { t } from '@lingui/core/macro';-import { getSendableEmailHandles, isDefined } from 'twenty-shared/utils';+import {+ canConnectedAccountPerformEmailOperation,+ getSendableEmailHandles,+ isDefined,+} from 'twenty-shared/utils';import { IconPaperclip } from 'twenty-ui/icon';import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';@@ -23,7 +28,6 @@ import { type EmailRecipientsByFieldId } from '@/activities/emails/recipients/utimport { type EmailComposerState } from '@/activities/emails/types/EmailComposerState';import { type ConnectedAccount } from '@/accounts/types/ConnectedAccount';import { buildConnectedAccountSenderOptions } from '@/accounts/utils/buildConnectedAccountSenderOptions';-import { canConnectedAccountSendEmail } from '@/accounts/utils/canConnectedAccountSendEmail';import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';import { Select } from '@/ui/input/components/Select';import { DND_KIT_PROVIDER_PLUGINS_WITHOUT_DROP_ANIMATION } from '@/ui/utilities/drag-and-drop/constants/DndKitProviderPluginsWithoutDropAnimation';@@ -121,7 +125,11 @@ export const EmailComposerFields = ({}>(GET_MY_CONNECTED_ACCOUNTS);const sendableAccounts = (accountsData?.myConnectedAccounts ?? []).filter(- canConnectedAccountSendEmail,+ (connectedAccount) =>+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.SEND,+ }),);const senderOptions = buildConnectedAccountSenderOptions(sendableAccounts);diff --git a/packages/twenty-front/src/modules/activities/emails/hooks/useFirstConnectedAccount.ts b/packages/twenty-front/src/modules/activities/emails/hooks/useFirstConnectedAccount.tsindex 583e8a93a3f..45380bbb812 100644--- a/packages/twenty-front/src/modules/activities/emails/hooks/useFirstConnectedAccount.ts+++ b/packages/twenty-front/src/modules/activities/emails/hooks/useFirstConnectedAccount.ts@@ -1,6 +1,9 @@+import { EmailOperation } from 'twenty-shared/types';import { useQuery } from '@apollo/client/react';+import { type ConnectedAccount } from '@/accounts/types/ConnectedAccount';import { GET_MY_CONNECTED_ACCOUNTS } from '@/settings/accounts/graphql/queries/getMyConnectedAccounts';+import { canConnectedAccountPerformEmailOperation } from 'twenty-shared/utils';type UseFirstConnectedAccountOptions = {skip?: boolean;@@ -10,12 +13,21 @@ export const useFirstConnectedAccount = (options?: UseFirstConnectedAccountOptions,) => {const { data, loading } = useQuery<{- myConnectedAccounts: { id: string; handle: string }[];+ myConnectedAccounts: Pick<+ ConnectedAccount,+ 'id' | 'handle' | 'provider' | 'connectionParameters'+ >[];}>(GET_MY_CONNECTED_ACCOUNTS, {skip: options?.skip,});- const firstAccount = data?.myConnectedAccounts?.[0] ?? null;+ const firstAccount =+ data?.myConnectedAccounts?.find((connectedAccount) =>+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.SEND,+ }),+ ) ?? null;return {connectedAccountId: firstAccount?.id ?? null,diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionEmailBase.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionEmailBase.tsxindex 6a0cd61566f..85a8b97e59e 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionEmailBase.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionEmailBase.tsx@@ -1,6 +1,5 @@import { type ConnectedAccount } from '@/accounts/types/ConnectedAccount';import { buildConnectedAccountSenderOptions } from '@/accounts/utils/buildConnectedAccountSenderOptions';-import { canConnectedAccountSendEmail } from '@/accounts/utils/canConnectedAccountSendEmail';import { getMissingDraftEmailScopes } from '@/accounts/utils/hasMissingDraftEmailScopes';import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';import { FormMultiTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormMultiTextFieldInput';@@ -30,8 +29,16 @@ import { WorkflowVariablePicker } from '@/workflow/workflow-variables/componentsimport { useQuery } from '@apollo/client/react';import { t } from '@lingui/core/macro';import { useEffect, useState } from 'react';-import { ConnectedAccountProvider, SettingsPath } from 'twenty-shared/types';-import { getSendableEmailHandles, isDefined } from 'twenty-shared/utils';+import {+ ConnectedAccountProvider,+ EmailOperation,+ SettingsPath,+} from 'twenty-shared/types';+import {+ canConnectedAccountPerformEmailOperation,+ getSendableEmailHandles,+ isDefined,+} from 'twenty-shared/utils';import { Callout } from 'twenty-ui/feedback';import { IconPlus } from 'twenty-ui/icon';import { isNonEmptyString } from '@sniptt/guards';@@ -164,7 +171,12 @@ export const WorkflowEditActionEmailBase = ({: null;const sendableAccounts = [- ...myAccounts.filter(canConnectedAccountSendEmail),+ ...myAccounts.filter((connectedAccount) =>+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.SEND,+ }),+ ),...(isDefined(otherAccount) ? [otherAccount] : []),];diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/draft-email-tool.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/draft-email-tool.tsindex 2c52165bd45..8b22ca75e98 100644--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/draft-email-tool.ts+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/draft-email-tool.ts@@ -1,3 +1,4 @@+import { EmailOperation } from 'twenty-shared/types';import { Injectable, Logger } from '@nestjs/common';import { EmailComposerService } from 'src/engine/core-modules/tool/tools/email-tool/email-composer.service';@@ -30,10 +31,11 @@ export class DraftEmailTool implements Tool {context: ToolExecutionContext,): Promise<ToolOutput> {try {- const result = await this.emailComposerService.composeEmail(+ const result = await this.emailComposerService.composeEmail({parameters,context,- );+ operation: EmailOperation.DRAFT,+ });if (!result.success) {return result.output;diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.tsindex f6c2598bc76..24773c631ef 100644--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts@@ -6,8 +6,15 @@ import { MAX_EMAIL_RECIPIENTS } from 'twenty-shared/constants';import {ConnectedAccountProvider,type EmailAttachment,+ EmailOperation,} from 'twenty-shared/types';-import { isDefined, isNonEmptyArray, isValidUuid } from 'twenty-shared/utils';+import {+ canConnectedAccountPerformEmailOperation,+ getEmailProvidersForOperation,+ isDefined,+ isNonEmptyArray,+ isValidUuid,+} from 'twenty-shared/utils';import { In, IsNull, LessThanOrEqual, type Repository } from 'typeorm';import { z } from 'zod';@@ -56,9 +63,11 @@ export class EmailComposerService {private async getConnectedAccountOrThrow({connectedAccountId,workspaceId,+ operation,}: {connectedAccountId: string;workspaceId: string;+ operation: EmailOperation;}): Promise<ConnectedAccountEntity> {if (!isValidUuid(connectedAccountId)) {throw new EmailToolException(@@ -71,7 +80,7 @@ export class EmailComposerService {return this.workspaceOrmManager.executeInWorkspaceContext(async () => {const connectedAccount = await this.connectedAccountRepository.findOne({- where: { id: connectedAccountId, workspaceId },+ where: { id: connectedAccountId, workspaceId, archivedAt: IsNull() },relations: {messageChannels: {messageFolders: true,@@ -86,6 +95,18 @@ export class EmailComposerService {);}+ if (+ !canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation,+ })+ ) {+ throw new EmailToolException(+ `Connected account '${connectedAccount.handle}' (${connectedAccount.provider}) cannot ${operation.toLowerCase()} email`,+ EmailToolExceptionCode.CONNECTED_ACCOUNT_NOT_EMAIL_CAPABLE,+ );+ }+return connectedAccount;}, authContext);}@@ -93,38 +114,51 @@ export class EmailComposerService {private async getDefaultConnectedAccountIdOrThrow({workspaceId,userWorkspaceId,+ operation,}: {workspaceId: string;userWorkspaceId?: string;+ operation: EmailOperation;}): Promise<string> {const authContext = buildSystemAuthContext(workspaceId);return this.workspaceOrmManager.executeInWorkspaceContext(async () => {- const allAccounts = await this.connectedAccountRepository.find({- where: { workspaceId, archivedAt: IsNull() },+ const mailboxes = await this.connectedAccountRepository.find({+ where: {+ workspaceId,+ archivedAt: IsNull(),+ provider: In(getEmailProvidersForOperation(operation)),+ },order: { createdAt: 'ASC', id: 'ASC' },});- if (!isNonEmptyArray(allAccounts)) {+ const usableMailboxes = mailboxes.filter((connectedAccount) =>+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation,+ }),+ );++ if (!isNonEmptyArray(usableMailboxes)) {throw new EmailToolException(- 'No connected accounts found for this workspace',- EmailToolExceptionCode.CONNECTED_ACCOUNT_NOT_FOUND,+ `No connected account in this workspace can ${operation.toLowerCase()} email`,+ EmailToolExceptionCode.NO_EMAIL_CAPABLE_CONNECTED_ACCOUNT,);}if (!isDefined(userWorkspaceId)) {- return allAccounts[0].id;+ return usableMailboxes[0].id;}const connectedAccountId = selectConnectedAccountIdForCaller({- connectedAccounts: allAccounts,+ connectedAccounts: usableMailboxes,userWorkspaceId,});if (!isDefined(connectedAccountId)) {throw new EmailToolException(- `No connected account available for user workspace '${userWorkspaceId}'`,- EmailToolExceptionCode.CONNECTED_ACCOUNT_NOT_FOUND,+ `No connected account available for user workspace '${userWorkspaceId}' that can ${operation.toLowerCase()} email`,+ EmailToolExceptionCode.NO_EMAIL_CAPABLE_CONNECTED_ACCOUNT,);}@@ -322,10 +356,15 @@ export class EmailComposerService {}, authContext);}- async composeEmail(- parameters: ComposeEmailParams,- context: ToolExecutionContext,- ): Promise<EmailComposerResult> {+ async composeEmail({+ parameters,+ context,+ operation,+ }: {+ parameters: ComposeEmailParams;+ context: ToolExecutionContext;+ operation: EmailOperation;+ }): Promise<EmailComposerResult> {const { workspaceId, userWorkspaceId } = context;const { subject, body, files, inReplyTo, fromHandle } = parameters;let { connectedAccountId } = parameters;@@ -368,12 +407,14 @@ export class EmailComposerService {connectedAccountId = await this.getDefaultConnectedAccountIdOrThrow({workspaceId,userWorkspaceId,+ operation,});}const connectedAccount = await this.getConnectedAccountOrThrow({connectedAccountId,workspaceId,+ operation,});const messageChannel =@@ -387,16 +428,6 @@ export class EmailComposerService {connectedAccount.provider === ConnectedAccountProvider.IMAP_SMTP_CALDAV &&!isDefined(connectedAccount.connectionParameters?.IMAP);- if (- isSmtpOnlyAccount &&- !isDefined(connectedAccount.connectionParameters?.SMTP)- ) {- throw new EmailToolException(- `SMTP is not configured for connected account '${connectedAccountId}'`,- EmailToolExceptionCode.CONNECTED_ACCOUNT_NOT_FOUND,- );- }-if (!isSmtpOnlyAccount && !isDefined(messageChannel)) {throw new EmailToolException(`No message channel found for connected account '${connectedAccountId}'`,diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-tool.schema.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-tool.schema.tsindex 64ebc7b4744..7f3bb10560a 100644--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-tool.schema.ts+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-tool.schema.ts@@ -33,7 +33,7 @@ export const EmailToolInputZodSchema = z.object({.string().refine((val) => isValidUuid(val)).describe(- 'The UUID of the connected account to send the email from. Provide this only if you have it; otherwise, leave blank.',+ 'The UUID of the connected account to send the email from. When the user has not said which address to send from, call find_connected_accounts first: if it returns exactly one account use that id, and if it returns several ask the user which one before sending. Leave blank only when no account id could be determined.',).optional(),fromHandle: zdiff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/exceptions/email-tool.exception.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/exceptions/email-tool.exception.tsindex e6bd48db1f3..f43a713f1a1 100644--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/exceptions/email-tool.exception.ts+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/exceptions/email-tool.exception.ts@@ -12,6 +12,8 @@ export enum EmailToolExceptionCode {FILE_NOT_FOUND = 'FILE_NOT_FOUND',INVALID_FILE_ID = 'INVALID_FILE_ID',TOO_MANY_RECIPIENTS = 'TOO_MANY_RECIPIENTS',+ NO_EMAIL_CAPABLE_CONNECTED_ACCOUNT = 'NO_EMAIL_CAPABLE_CONNECTED_ACCOUNT',+ CONNECTED_ACCOUNT_NOT_EMAIL_CAPABLE = 'CONNECTED_ACCOUNT_NOT_EMAIL_CAPABLE',}const getEmailToolExceptionUserFriendlyMessage = (@@ -32,6 +34,10 @@ const getEmailToolExceptionUserFriendlyMessage = (return msg`Invalid file ID.`;case EmailToolExceptionCode.TOO_MANY_RECIPIENTS:return msg`Too many recipients.`;+ case EmailToolExceptionCode.NO_EMAIL_CAPABLE_CONNECTED_ACCOUNT:+ return msg`No mailbox is connected for this action. Connect one in Settings.`;+ case EmailToolExceptionCode.CONNECTED_ACCOUNT_NOT_EMAIL_CAPABLE:+ return msg`This connected account cannot be used for this action.`;default:assertUnreachable(code);}diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/find-connected-accounts-tool.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/find-connected-accounts-tool.tsindex 0446db9b16a..4b9466b64e4 100644--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/find-connected-accounts-tool.ts+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/find-connected-accounts-tool.ts@@ -1,3 +1,4 @@+import { EmailOperation } from 'twenty-shared/types';import { Injectable } from '@nestjs/common';import { isNonEmptyString } from '@sniptt/guards';@@ -13,7 +14,7 @@ import { ConnectedAccountMetadataService } from 'src/engine/metadata-modules/con@Injectable()export class FindConnectedAccountsTool implements Tool {description =- 'List connected email accounts the caller can use with draft_email and send_email. Returns id, handle, provider, visibility and aliases. Use a returned id as connectedAccountId.';+ 'List the mailboxes the caller can use with draft_email and send_email. Returns id, handle, provider, visibility and aliases. Pass a returned id as connectedAccountId. If more than one is returned, ask the user which one to send from rather than guessing. Whether a given mailbox supports drafting also depends on its configuration, which draft_email reports if it does not.';inputSchema = FindConnectedAccountsToolInputZodSchema;constructor(@@ -24,18 +25,19 @@ export class FindConnectedAccountsTool implements Tool {{ handle }: FindConnectedAccountsToolInput,{ workspaceId, userWorkspaceId }: ToolExecutionContext,): Promise<ToolOutput> {- const usableAccounts =- await this.connectedAccountMetadataService.findUsableByCaller({+ const mailboxAccounts =+ await this.connectedAccountMetadataService.findMailboxesUsableByCaller({workspaceId,userWorkspaceId,+ operation: EmailOperation.SEND,});const matchingAccounts = isNonEmptyString(handle)? filterConnectedAccountsByHandle({- connectedAccounts: usableAccounts,+ connectedAccounts: mailboxAccounts,handle,})- : usableAccounts;+ : mailboxAccounts;const records = matchingAccounts.map((connectedAccount) => ({id: connectedAccount.id,diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/send-email-tool.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/send-email-tool.tsindex efb467a0793..b4e252df269 100644--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/send-email-tool.ts+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/send-email-tool.ts@@ -1,3 +1,4 @@+import { EmailOperation } from 'twenty-shared/types';import { Injectable, Logger } from '@nestjs/common';import { EmailComposerService } from 'src/engine/core-modules/tool/tools/email-tool/email-composer.service';@@ -28,10 +29,11 @@ export class SendEmailTool implements Tool {context: ToolExecutionContext,): Promise<ToolOutput> {try {- const result = await this.emailComposerService.composeEmail(+ const result = await this.emailComposerService.composeEmail({parameters,context,- );+ operation: EmailOperation.SEND,+ });if (!result.success) {return result.output;diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.tsindex d7884481949..cec865ca5cc 100644--- a/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts@@ -3,8 +3,12 @@ import { InjectRepository } from '@nestjs/typeorm';import { In, IsNull, Repository } from 'typeorm';-import { ConnectedAccountProvider } from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';+import { ConnectedAccountProvider, EmailOperation } from 'twenty-shared/types';+import {+ canConnectedAccountPerformEmailOperation,+ getEmailProvidersForOperation,+ isDefined,+} from 'twenty-shared/utils';import { ConnectionProviderLifecycleHookService } from 'src/engine/core-modules/application/connection-provider/connection-provider-lifecycle-hook.service';import { AppOAuthRevokeService } from 'src/engine/core-modules/application/connection-provider/refresh/services/app-oauth-revoke.service';@@ -18,7 +22,7 @@ import {} from 'src/engine/metadata-modules/connected-account/connected-account.exception';import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';import { type ConnectedAccountDeletedEvent } from 'src/engine/metadata-modules/connected-account/types/connected-account-deleted.type';-import { type ConnectedAccountWithoutCredentials } from 'src/engine/metadata-modules/connected-account/types/connected-account-without-credentials.type';+import { type ConnectedAccountUsableByCaller } from 'src/engine/metadata-modules/connected-account/types/connected-account-usable-by-caller.type';import { buildConnectedAccountUsableByCallerWhere } from 'src/engine/metadata-modules/connected-account/utils/build-connected-account-usable-by-caller-where.util';import { isConnectedAccountUsableByCaller } from 'src/engine/metadata-modules/connected-account/utils/is-connected-account-usable-by-caller.util';import { MESSAGE_CHANNEL_DELETED_EVENT } from 'src/engine/metadata-modules/message-channel/constants/message-channel-deleted.constant';@@ -42,15 +46,21 @@ export class ConnectedAccountMetadataService {private readonly workspaceEventEmitter: WorkspaceEventEmitter,) {}- async findUsableByCaller({+ async findMailboxesUsableByCaller({workspaceId,userWorkspaceId,+ operation,}: {workspaceId: string;userWorkspaceId?: string;- }): Promise<ConnectedAccountWithoutCredentials[]> {+ operation: EmailOperation;+ }): Promise<ConnectedAccountUsableByCaller[]> {const connectedAccounts = await this.repository.find({- where: { workspaceId, archivedAt: IsNull() },+ where: {+ workspaceId,+ archivedAt: IsNull(),+ provider: In(getEmailProvidersForOperation(operation)),+ },order: { createdAt: 'ASC', id: 'ASC' },select: {id: true,@@ -60,18 +70,25 @@ export class ConnectedAccountMetadataService {name: true,visibility: true,userWorkspaceId: true,+ connectionParameters: true,},});- if (!isDefined(userWorkspaceId)) {- return connectedAccounts.filter(- (connectedAccount) => connectedAccount.visibility === 'workspace',+ return connectedAccounts+ .filter((connectedAccount) =>+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation,+ }),+ )+ .filter((connectedAccount) =>+ isDefined(userWorkspaceId)+ ? isConnectedAccountUsableByCaller({+ connectedAccount,+ userWorkspaceId,+ })+ : connectedAccount.visibility === 'workspace',);- }-- return connectedAccounts.filter((connectedAccount) =>- isConnectedAccountUsableByCaller({ connectedAccount, userWorkspaceId }),- );}async findByUserWorkspaceId({diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/types/connected-account-usable-by-caller.type.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/types/connected-account-usable-by-caller.type.tsnew file mode 100644index 00000000000..20f1a656626--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/connected-account/types/connected-account-usable-by-caller.type.ts@@ -0,0 +1,6 @@+import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';+import { type ConnectedAccountWithoutCredentials } from 'src/engine/metadata-modules/connected-account/types/connected-account-without-credentials.type';++export type ConnectedAccountUsableByCaller =+ ConnectedAccountWithoutCredentials &+ Pick<ConnectedAccountEntity, 'connectionParameters'>;diff --git a/packages/twenty-server/src/modules/messaging/message-outbound-manager/resolvers/send-email.resolver.ts b/packages/twenty-server/src/modules/messaging/message-outbound-manager/resolvers/send-email.resolver.tsindex c06f36e8a30..5f6acabac3c 100644--- a/packages/twenty-server/src/modules/messaging/message-outbound-manager/resolvers/send-email.resolver.ts+++ b/packages/twenty-server/src/modules/messaging/message-outbound-manager/resolvers/send-email.resolver.ts@@ -1,3 +1,4 @@+import { EmailOperation } from 'twenty-shared/types';import {ForbiddenException,Logger,@@ -56,8 +57,8 @@ export class SendEmailResolver {workspaceId: workspace.id,});- const result = await this.emailComposerService.composeEmail(- {+ const result = await this.emailComposerService.composeEmail({+ parameters: {recipients: {to: input.to,cc: input.cc ?? '',@@ -70,8 +71,9 @@ export class SendEmailResolver {files: input.files ?? [],inReplyTo: input.inReplyTo,},- { workspaceId: workspace.id },- );+ context: { workspaceId: workspace.id },+ operation: EmailOperation.SEND,+ });if (!result.success) {return {diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/draft-email.workflow-action.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/draft-email.workflow-action.spec.tsindex 1bcddeff7a6..c2f1bf8d71b 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/draft-email.workflow-action.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/draft-email.workflow-action.spec.ts@@ -1,6 +1,7 @@import { Test, type TestingModule } from '@nestjs/testing';import { getRepositoryToken } from '@nestjs/typeorm';+import { ConnectedAccountProvider, EmailOperation } from 'twenty-shared/types';import { WorkflowActionType } from 'twenty-shared/workflow';import { DraftEmailTool } from 'src/engine/core-modules/tool/tools/email-tool/draft-email-tool';import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';@@ -38,7 +39,7 @@ describe('DraftEmailWorkflowAction', () => {let action: DraftEmailWorkflowAction;let mockDraftEmailTool: jest.Mocked<Pick<DraftEmailTool, 'execute'>>;let mockSetStepLog: jest.Mock;- let connectedAccountRepository: { findOne: jest.Mock };+ let connectedAccountRepository: { find: jest.Mock };let userWorkspaceRepository: { findOne: jest.Mock };let workspaceMemberRepository: { findOne: jest.Mock };@@ -52,7 +53,7 @@ describe('DraftEmailWorkflowAction', () => {}),};mockSetStepLog = jest.fn();- connectedAccountRepository = { findOne: jest.fn() };+ connectedAccountRepository = { find: jest.fn() };userWorkspaceRepository = { findOne: jest.fn() };workspaceMemberRepository = { findOne: jest.fn() };@@ -137,7 +138,7 @@ describe('DraftEmailWorkflowAction', () => {stepLog: expect.objectContaining({details: expect.objectContaining({type: 'EMAIL',- mode: 'DRAFT',+ mode: EmailOperation.DRAFT,}),}),}),@@ -165,9 +166,13 @@ describe('DraftEmailWorkflowAction', () => {userWorkspaceRepository.findOne.mockResolvedValue({id: USER_WORKSPACE_ID,});- connectedAccountRepository.findOne.mockResolvedValue({- id: MEMBER_ACCOUNT_ID,- });+ connectedAccountRepository.find.mockResolvedValue([+ {+ id: MEMBER_ACCOUNT_ID,+ provider: ConnectedAccountProvider.GOOGLE,+ connectionParameters: null,+ },+ ]);await executeWithSender(WORKSPACE_MEMBER_ID);@@ -182,7 +187,7 @@ describe('DraftEmailWorkflowAction', () => {await executeWithSender(WORKSPACE_MEMBER_ID);- expect(connectedAccountRepository.findOne).not.toHaveBeenCalled();+ expect(connectedAccountRepository.find).not.toHaveBeenCalled();expect(mockDraftEmailTool.execute).toHaveBeenCalledWith(expect.objectContaining({ connectedAccountId: WORKSPACE_MEMBER_ID }),expect.any(Object),@@ -194,10 +199,10 @@ describe('DraftEmailWorkflowAction', () => {userWorkspaceRepository.findOne.mockResolvedValue({id: USER_WORKSPACE_ID,});- connectedAccountRepository.findOne.mockResolvedValue(null);+ connectedAccountRepository.find.mockResolvedValue([]);await expect(executeWithSender(WORKSPACE_MEMBER_ID)).rejects.toThrow(- `No connected account found for workspace member '${WORKSPACE_MEMBER_ID}'`,+ `Workspace member '${WORKSPACE_MEMBER_ID}' has no connected account that can draft email`,);expect(mockDraftEmailTool.execute).not.toHaveBeenCalled();});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/send-email.workflow-action.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/send-email.workflow-action.spec.tsindex 3b76df5373c..fde5e757e6d 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/send-email.workflow-action.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/send-email.workflow-action.spec.ts@@ -1,6 +1,7 @@import { Test, type TestingModule } from '@nestjs/testing';import { getRepositoryToken } from '@nestjs/typeorm';+import { ConnectedAccountProvider } from 'twenty-shared/types';import { WorkflowActionType } from 'twenty-shared/workflow';import { SendEmailTool } from 'src/engine/core-modules/tool/tools/email-tool/send-email-tool';import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';@@ -43,7 +44,7 @@ const MEMBER_ACCOUNT_ID = '20202020-5555-4555-8555-555555555555';describe('SendEmailWorkflowAction', () => {let action: SendEmailWorkflowAction;let mockSendEmailTool: jest.Mocked<Pick<SendEmailTool, 'execute'>>;- let connectedAccountRepository: { findOne: jest.Mock };+ let connectedAccountRepository: { find: jest.Mock };let userWorkspaceRepository: { findOne: jest.Mock };let workspaceMemberRepository: { findOne: jest.Mock };@@ -56,7 +57,7 @@ describe('SendEmailWorkflowAction', () => {error: undefined,}),};- connectedAccountRepository = { findOne: jest.fn() };+ connectedAccountRepository = { find: jest.fn() };userWorkspaceRepository = { findOne: jest.fn() };workspaceMemberRepository = { findOne: jest.fn() };@@ -346,9 +347,65 @@ describe('SendEmailWorkflowAction', () => {userWorkspaceRepository.findOne.mockResolvedValue({id: USER_WORKSPACE_ID,});- connectedAccountRepository.findOne.mockResolvedValue({- id: MEMBER_ACCOUNT_ID,+ connectedAccountRepository.find.mockResolvedValue([+ {+ id: MEMBER_ACCOUNT_ID,+ provider: ConnectedAccountProvider.GOOGLE,+ connectionParameters: null,+ },+ ]);++ await executeWithSender(WORKSPACE_MEMBER_ID);++ expect(mockSendEmailTool.execute).toHaveBeenCalledWith(+ expect.objectContaining({ connectedAccountId: MEMBER_ACCOUNT_ID }),+ expect.any(Object),+ );+ });++ it('skips an older application connection and picks the member mailbox', async () => {+ workspaceMemberRepository.findOne.mockResolvedValue({ userId: 'user-1' });+ userWorkspaceRepository.findOne.mockResolvedValue({+ id: USER_WORKSPACE_ID,});+ connectedAccountRepository.find.mockResolvedValue([+ {+ id: 'app-connection-id',+ provider: ConnectedAccountProvider.APP,+ connectionParameters: null,+ },+ {+ id: MEMBER_ACCOUNT_ID,+ provider: ConnectedAccountProvider.GOOGLE,+ connectionParameters: null,+ },+ ]);++ await executeWithSender(WORKSPACE_MEMBER_ID);++ expect(mockSendEmailTool.execute).toHaveBeenCalledWith(+ expect.objectContaining({ connectedAccountId: MEMBER_ACCOUNT_ID }),+ expect.any(Object),+ );+ });++ it('skips an imap account with no SMTP configured', async () => {+ workspaceMemberRepository.findOne.mockResolvedValue({ userId: 'user-1' });+ userWorkspaceRepository.findOne.mockResolvedValue({+ id: USER_WORKSPACE_ID,+ });+ connectedAccountRepository.find.mockResolvedValue([+ {+ id: 'imap-without-smtp-id',+ provider: ConnectedAccountProvider.IMAP_SMTP_CALDAV,+ connectionParameters: { IMAP: { host: 'imap.example.com' } },+ },+ {+ id: MEMBER_ACCOUNT_ID,+ provider: ConnectedAccountProvider.GOOGLE,+ connectionParameters: null,+ },+ ]);await executeWithSender(WORKSPACE_MEMBER_ID);@@ -363,7 +420,7 @@ describe('SendEmailWorkflowAction', () => {await executeWithSender(WORKSPACE_MEMBER_ID);- expect(connectedAccountRepository.findOne).not.toHaveBeenCalled();+ expect(connectedAccountRepository.find).not.toHaveBeenCalled();expect(mockSendEmailTool.execute).toHaveBeenCalledWith(expect.objectContaining({ connectedAccountId: WORKSPACE_MEMBER_ID }),expect.any(Object),@@ -415,10 +472,10 @@ describe('SendEmailWorkflowAction', () => {userWorkspaceRepository.findOne.mockResolvedValue({id: USER_WORKSPACE_ID,});- connectedAccountRepository.findOne.mockResolvedValue(null);+ connectedAccountRepository.find.mockResolvedValue([]);await expect(executeWithSender(WORKSPACE_MEMBER_ID)).rejects.toThrow(- `No connected account found for workspace member '${WORKSPACE_MEMBER_ID}'`,+ `Workspace member '${WORKSPACE_MEMBER_ID}' has no connected account that can send email`,);expect(mockSendEmailTool.execute).not.toHaveBeenCalled();});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/draft-email.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/draft-email.workflow-action.tsindex adc0c40ff5c..11af6b0baff 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/draft-email.workflow-action.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/draft-email.workflow-action.ts@@ -1,4 +1,5 @@import { Injectable } from '@nestjs/common';+import { EmailOperation } from 'twenty-shared/types';import { InjectRepository } from '@nestjs/typeorm';import { type Repository } from 'typeorm';@@ -15,7 +16,6 @@ import {import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';import { EmailWorkflowActionBase } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base';import { isWorkflowDraftEmailAction } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/guards/is-workflow-draft-email-action.guard';-import { type EmailStepLogMode } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/build-email-step-log.util';import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';import { WorkflowRunStepLogWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service';@@ -45,8 +45,8 @@ export class DraftEmailWorkflowAction extends EmailWorkflowActionBase {return this.draftEmailTool;}- protected getMode(): EmailStepLogMode {- return 'DRAFT';+ protected getMode(): EmailOperation {+ return EmailOperation.DRAFT;}protected assertStep(step: WorkflowAction): void {diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.tsindex bb80cb73afa..fb3f95248a3 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts@@ -1,6 +1,8 @@+import { type EmailOperation } from 'twenty-shared/types';import { type WorkflowRunStepLog } from 'twenty-shared/workflow';import {+ canConnectedAccountPerformEmailOperation,isDefined,isValidUuid,resolveInput as resolveWorkflowInput,@@ -21,10 +23,7 @@ import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-eimport { type WorkflowRunInfo } from 'src/modules/workflow/workflow-executor/types/workflow-action-input';import { getUserFromAuthContext } from 'src/modules/workflow/workflow-executor/utils/get-user-from-auth-context.util';import { type WorkflowSendEmailActionInput } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/types/workflow-send-email-action-input.type';-import {- buildEmailStepLog,- type EmailStepLogMode,-} from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/build-email-step-log.util';+import { buildEmailStepLog } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/build-email-step-log.util';import { resolveEmailBody } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/resolve-email-body.util';import { resolveEmailFiles } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/resolve-email-files.util';import { ToolBackedWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/tool-backed/tool-backed.workflow-action';@@ -43,7 +42,7 @@ export abstract class EmailWorkflowActionBase extends ToolBackedWorkflowAction<Wsuper(loggerName, workflowRunStepLogService);}- protected abstract getMode(): EmailStepLogMode;+ protected abstract getMode(): EmailOperation;protected override async preprocessInput(rawInput: WorkflowSendEmailActionInput,@@ -131,7 +130,7 @@ export abstract class EmailWorkflowActionBase extends ToolBackedWorkflowAction<Wif (!isDefined(connectedAccountId)) {throw new WorkflowStepExecutorException(- `No connected account found for workspace member '${senderId}'`,+ `Workspace member '${senderId}' has no connected account that can ${this.getMode().toLowerCase()} email`,WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,);}@@ -166,16 +165,22 @@ export abstract class EmailWorkflowActionBase extends ToolBackedWorkflowAction<Wreturn null;}- const connectedAccount = await this.connectedAccountRepository.findOne({+ const connectedAccounts = await this.connectedAccountRepository.find({where: {userWorkspaceId: userWorkspace.id,workspaceId,archivedAt: IsNull(),},- order: { createdAt: 'ASC' },+ order: { createdAt: 'ASC', id: 'ASC' },});- return connectedAccount?.id ?? null;+ const operation = this.getMode();++ const emailCapableAccount = connectedAccounts.find((connectedAccount) =>+ canConnectedAccountPerformEmailOperation({ connectedAccount, operation }),+ );++ return emailCapableAccount?.id ?? null;}protected buildStepLog({diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/send-email.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/send-email.workflow-action.tsindex f48199ec29e..97d900e4378 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/send-email.workflow-action.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/send-email.workflow-action.ts@@ -1,4 +1,5 @@import { Injectable } from '@nestjs/common';+import { EmailOperation } from 'twenty-shared/types';import { InjectRepository } from '@nestjs/typeorm';import { type Repository } from 'typeorm';@@ -15,7 +16,6 @@ import {import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';import { EmailWorkflowActionBase } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base';import { isWorkflowSendEmailAction } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/guards/is-workflow-send-email-action.guard';-import { type EmailStepLogMode } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/build-email-step-log.util';import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';import { WorkflowRunStepLogWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service';@@ -45,8 +45,8 @@ export class SendEmailWorkflowAction extends EmailWorkflowActionBase {return this.sendEmailTool;}- protected getMode(): EmailStepLogMode {- return 'SEND';+ protected getMode(): EmailOperation {+ return EmailOperation.SEND;}protected assertStep(step: WorkflowAction): void {diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/__tests__/build-email-step-log.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/__tests__/build-email-step-log.util.spec.tsindex a82a8ff60a8..356abfa0020 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/__tests__/build-email-step-log.util.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/__tests__/build-email-step-log.util.spec.ts@@ -1,3 +1,5 @@+import { EmailOperation } from 'twenty-shared/types';+import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';import { type WorkflowSendEmailActionInput } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/types/workflow-send-email-action-input.type';import { buildEmailStepLog } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/build-email-step-log.util';@@ -25,7 +27,7 @@ const successOutput: ToolOutput = {describe('buildEmailStepLog', () => {it('builds a SUCCESS email log preferring parsed recipients from the tool output', () => {const stepLog = buildEmailStepLog({- mode: 'SEND',+ mode: EmailOperation.SEND,input: baseInput,output: successOutput,durationMs: 120,@@ -35,7 +37,7 @@ describe('buildEmailStepLog', () => {throw new Error('Expected EMAIL details');}- expect(stepLog.details.mode).toBe('SEND');+ expect(stepLog.details.mode).toBe(EmailOperation.SEND);expect(stepLog.details.status).toBe('SUCCESS');expect(stepLog.details.recipients.to).toEqual([@@ -49,7 +51,7 @@ describe('buildEmailStepLog', () => {it('falls back to splitting the comma-separated input when the tool output has no parsed recipients', () => {const stepLog = buildEmailStepLog({- mode: 'DRAFT',+ mode: EmailOperation.DRAFT,input: {...baseInput,recipients: {@@ -69,7 +71,7 @@ describe('buildEmailStepLog', () => {throw new Error('Expected EMAIL details');}- expect(stepLog.details.mode).toBe('DRAFT');+ expect(stepLog.details.mode).toBe(EmailOperation.DRAFT);expect(stepLog.details.status).toBe('ERROR');expect(stepLog.details.recipients.to).toEqual([@@ -84,7 +86,7 @@ describe('buildEmailStepLog', () => {const longBody = `<p>${'x'.repeat(20_000)}</p>`;const stepLog = buildEmailStepLog({- mode: 'SEND',+ mode: EmailOperation.SEND,input: { ...baseInput, body: longBody },output: successOutput,durationMs: 10,@@ -101,7 +103,7 @@ describe('buildEmailStepLog', () => {it('prefers the sanitized HTML body from the tool output over the raw input body', () => {const stepLog = buildEmailStepLog({- mode: 'SEND',+ mode: EmailOperation.SEND,input: {...baseInput,body: '<script>alert("xss")</script><p>Hello</p>',@@ -127,7 +129,7 @@ describe('buildEmailStepLog', () => {it('falls back to the raw input body when the tool failed before composing', () => {const stepLog = buildEmailStepLog({- mode: 'SEND',+ mode: EmailOperation.SEND,input: { ...baseInput, body: '<p>Hello</p>' },output: {success: false,@@ -146,7 +148,7 @@ describe('buildEmailStepLog', () => {it('omits cc/bcc when neither input nor output provides them', () => {const stepLog = buildEmailStepLog({- mode: 'SEND',+ mode: EmailOperation.SEND,input: { ...baseInput, recipients: { to: '[email protected]' } },output: successOutput,durationMs: 10,diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/build-email-step-log.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/build-email-step-log.util.tsindex 0e5faf7f955..b1a1ccbf30b 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/build-email-step-log.util.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/build-email-step-log.util.ts@@ -1,3 +1,4 @@+import { type EmailOperation } from 'twenty-shared/types';import { type WorkflowRunStepLog } from 'twenty-shared/workflow';import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';@@ -6,8 +7,6 @@ import { truncateStringToUtf8ByteBudget } from 'src/utils/truncate-string-to-utfconst MAX_BODY_PREVIEW_BYTES = 8_000;-export type EmailStepLogMode = 'SEND' | 'DRAFT';-const splitRecipients = (raw: string | undefined): string[] => {if (raw === undefined || raw === null) {return [];@@ -88,7 +87,7 @@ export const buildEmailStepLog = ({output,durationMs,}: {- mode: EmailStepLogMode;+ mode: EmailOperation;input: WorkflowSendEmailActionInput;output: ToolOutput;durationMs: number;diff --git a/packages/twenty-server/test/integration/email-tool/suites/email-composer-connected-account.integration-spec.ts b/packages/twenty-server/test/integration/email-tool/suites/email-composer-connected-account.integration-spec.tsindex 0d2b67053ec..ed8b5c6e339 100644--- a/packages/twenty-server/test/integration/email-tool/suites/email-composer-connected-account.integration-spec.ts+++ b/packages/twenty-server/test/integration/email-tool/suites/email-composer-connected-account.integration-spec.ts@@ -1,3 +1,4 @@+import { EmailOperation } from 'twenty-shared/types';import { EmailComposerService } from 'src/engine/core-modules/tool/tools/email-tool/email-composer.service';import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';@@ -23,6 +24,7 @@ const getFirstWorkspaceConnectedAccountId = async (): Promise<string> => {const [{ id }] = await global.testDataSource.query(`SELECT id FROM core."connectedAccount"WHERE "workspaceId" = $1 AND "archivedAt" IS NULL+ AND provider NOT IN ('app', 'oidc', 'saml')ORDER BY "createdAt" ASC, id ASCLIMIT 1`,[WORKSPACE_ID],@@ -31,9 +33,20 @@ const getFirstWorkspaceConnectedAccountId = async (): Promise<string> => {return id;};+const readConnectedAccountState = async (+ connectedAccountId: string,+): Promise<{ visibility: string; archivedAt: string | null }> => {+ const [state] = await global.testDataSource.query(+ `SELECT visibility, "archivedAt" FROM core."connectedAccount" WHERE id = $1`,+ [connectedAccountId],+ );++ return state;+};+const setVisibility = async (connectedAccountId: string,- visibility: 'user' | 'workspace',+ visibility: string,) => {await global.testDataSource.query(`UPDATE core."connectedAccount" SET visibility = $1 WHERE id = $2`,@@ -41,6 +54,55 @@ const setVisibility = async ();};+const insertConnectedAccount = async ({+ id,+ provider,+ userWorkspaceId,+ visibility = 'user',+}: {+ id: string;+ provider: 'app' | 'oidc' | 'saml' | 'email_group';+ userWorkspaceId: string;+ visibility?: 'user' | 'workspace';+}) => {+ await global.testDataSource.query(+ `INSERT INTO core."connectedAccount"+ (id, handle, provider, "userWorkspaceId", "workspaceId", visibility, "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, '1970-01-01T00:00:00Z', now())`,+ [+ id,+ `${provider}@example.com`,+ provider,+ userWorkspaceId,+ WORKSPACE_ID,+ visibility,+ ],+ );+};++const insertNonMailboxConnectedAccount = async (params: {+ id: string;+ provider: 'app' | 'oidc' | 'saml';+ userWorkspaceId: string;+}) => insertConnectedAccount(params);++const deleteConnectedAccount = async (connectedAccountId: string) => {+ await global.testDataSource.query(+ `DELETE FROM core."connectedAccount" WHERE id = $1`,+ [connectedAccountId],+ );+};++const setArchivedAt = async (+ connectedAccountId: string,+ archivedAt: string | null,+) => {+ await global.testDataSource.query(+ `UPDATE core."connectedAccount" SET "archivedAt" = $1 WHERE id = $2`,+ [archivedAt, connectedAccountId],+ );+};+describe('EmailComposerService connected account resolution (integration)', () => {let service: EmailComposerService;@@ -52,10 +114,17 @@ describe('EmailComposerService connected account resolution (integration)', () =describe('when the caller names a connected account', () => {it('uses that account, whoever owns it', async () => {- const result = await service.composeEmail(- { ...baseParams, connectedAccountId: JONY_CONNECTED_ACCOUNT_ID },- { workspaceId: WORKSPACE_ID, userWorkspaceId: PHIL_USER_WORKSPACE_ID },- );+ const result = await service.composeEmail({+ parameters: {+ ...baseParams,+ connectedAccountId: JONY_CONNECTED_ACCOUNT_ID,+ },+ context: {+ workspaceId: WORKSPACE_ID,+ userWorkspaceId: PHIL_USER_WORKSPACE_ID,+ },+ operation: EmailOperation.SEND,+ });expect(result.success).toBe(true);expect(result.success && result.data.connectedAccount.id).toBe(@@ -64,10 +133,14 @@ describe('EmailComposerService connected account resolution (integration)', () =});it('uses that account when there is no caller (workflow run)', async () => {- const result = await service.composeEmail(- { ...baseParams, connectedAccountId: JONY_CONNECTED_ACCOUNT_ID },- { workspaceId: WORKSPACE_ID },- );+ const result = await service.composeEmail({+ parameters: {+ ...baseParams,+ connectedAccountId: JONY_CONNECTED_ACCOUNT_ID,+ },+ context: { workspaceId: WORKSPACE_ID },+ operation: EmailOperation.SEND,+ });expect(result.success).toBe(true);expect(result.success && result.data.connectedAccount.id).toBe(@@ -77,34 +150,139 @@ describe('EmailComposerService connected account resolution (integration)', () =it('throws when the id is not a valid UUID', async () => {await expect(- service.composeEmail(- { ...baseParams, connectedAccountId: 'not-a-uuid' },- {+ service.composeEmail({+ parameters: { ...baseParams, connectedAccountId: 'not-a-uuid' },+ context: {workspaceId: WORKSPACE_ID,userWorkspaceId: PHIL_USER_WORKSPACE_ID,},- ),+ operation: EmailOperation.SEND,+ }),).rejects.toThrow('Connected account id is not a valid UUID');});it('throws when no connected account matches the id', async () => {await expect(- service.composeEmail(- { ...baseParams, connectedAccountId: UNKNOWN_CONNECTED_ACCOUNT_ID },- {+ service.composeEmail({+ parameters: {+ ...baseParams,+ connectedAccountId: UNKNOWN_CONNECTED_ACCOUNT_ID,+ },+ context: {workspaceId: WORKSPACE_ID,userWorkspaceId: PHIL_USER_WORKSPACE_ID,},- ),+ operation: EmailOperation.SEND,+ }),).rejects.toThrow('No connected account found for id');});++ it('refuses an application connection that cannot carry mail', async () => {+ const appConnectedAccountId = '20202020-0000-4000-8000-0000000000a1';++ await insertNonMailboxConnectedAccount({+ id: appConnectedAccountId,+ provider: 'app',+ userWorkspaceId: PHIL_USER_WORKSPACE_ID,+ });++ try {+ await expect(+ service.composeEmail({+ parameters: {+ ...baseParams,+ connectedAccountId: appConnectedAccountId,+ },+ context: {+ workspaceId: WORKSPACE_ID,+ userWorkspaceId: PHIL_USER_WORKSPACE_ID,+ },+ operation: EmailOperation.SEND,+ }),+ ).rejects.toThrow('cannot send email');+ } finally {+ await deleteConnectedAccount(appConnectedAccountId);+ }+ });++ it('refuses an archived account named explicitly', async () => {+ const { archivedAt } = await readConnectedAccountState(+ JONY_CONNECTED_ACCOUNT_ID,+ );++ await setArchivedAt(JONY_CONNECTED_ACCOUNT_ID, new Date().toISOString());++ try {+ await expect(+ service.composeEmail({+ parameters: {+ ...baseParams,+ connectedAccountId: JONY_CONNECTED_ACCOUNT_ID,+ },+ context: { workspaceId: WORKSPACE_ID },+ operation: EmailOperation.SEND,+ }),+ ).rejects.toThrow('No connected account found for id');+ } finally {+ await setArchivedAt(JONY_CONNECTED_ACCOUNT_ID, archivedAt);+ }+ });+ });++ describe('when drafting rather than sending', () => {+ it('composes a draft from the caller own mailbox', async () => {+ const result = await service.composeEmail({+ parameters: baseParams,+ context: {+ workspaceId: WORKSPACE_ID,+ userWorkspaceId: PHIL_USER_WORKSPACE_ID,+ },+ operation: EmailOperation.DRAFT,+ });++ expect(result.success).toBe(true);+ expect(result.success && result.data.connectedAccount.id).toBe(+ PHIL_CONNECTED_ACCOUNT_ID,+ );+ });++ it('refuses an email group, which has no drafts folder', async () => {+ const emailGroupConnectedAccountId =+ '20202020-0000-4000-8000-0000000000a4';++ await insertConnectedAccount({+ id: emailGroupConnectedAccountId,+ provider: 'email_group',+ userWorkspaceId: PHIL_USER_WORKSPACE_ID,+ visibility: 'workspace',+ });++ try {+ await expect(+ service.composeEmail({+ parameters: {+ ...baseParams,+ connectedAccountId: emailGroupConnectedAccountId,+ },+ context: { workspaceId: WORKSPACE_ID },+ operation: EmailOperation.DRAFT,+ }),+ ).rejects.toThrow('cannot draft email');+ } finally {+ await deleteConnectedAccount(emailGroupConnectedAccountId);+ }+ });});describe('when the caller names none', () => {it('composes from the caller own account rather than the first of the workspace', async () => {- const result = await service.composeEmail(baseParams, {- workspaceId: WORKSPACE_ID,- userWorkspaceId: PHIL_USER_WORKSPACE_ID,+ const result = await service.composeEmail({+ parameters: baseParams,+ context: {+ workspaceId: WORKSPACE_ID,+ userWorkspaceId: PHIL_USER_WORKSPACE_ID,+ },+ operation: EmailOperation.SEND,});expect(result.success).toBe(true);@@ -113,13 +291,80 @@ describe('EmailComposerService connected account resolution (integration)', () =);});+ it('skips an older application connection and still picks the mailbox', async () => {+ const appConnectedAccountId = '20202020-0000-4000-8000-0000000000a2';++ await insertNonMailboxConnectedAccount({+ id: appConnectedAccountId,+ provider: 'app',+ userWorkspaceId: PHIL_USER_WORKSPACE_ID,+ });++ try {+ const result = await service.composeEmail({+ parameters: baseParams,+ context: {+ workspaceId: WORKSPACE_ID,+ userWorkspaceId: PHIL_USER_WORKSPACE_ID,+ },+ operation: EmailOperation.SEND,+ });++ expect(result.success).toBe(true);+ expect(result.success && result.data.connectedAccount.id).toBe(+ PHIL_CONNECTED_ACCOUNT_ID,+ );+ } finally {+ await deleteConnectedAccount(appConnectedAccountId);+ }+ });++ it('skips an older SSO connection when there is no caller (workflow run)', async () => {+ const oidcConnectedAccountId = '20202020-0000-4000-8000-0000000000a3';++ await insertNonMailboxConnectedAccount({+ id: oidcConnectedAccountId,+ provider: 'oidc',+ userWorkspaceId: PHIL_USER_WORKSPACE_ID,+ });++ try {+ const firstWorkspaceConnectedAccountId =+ await getFirstWorkspaceConnectedAccountId();++ const result = await service.composeEmail({+ parameters: baseParams,+ context: { workspaceId: WORKSPACE_ID },+ operation: EmailOperation.SEND,+ });++ expect(result.success).toBe(true);+ expect(result.success && result.data.connectedAccount.id).toBe(+ firstWorkspaceConnectedAccountId,+ );+ expect(result.success && result.data.connectedAccount.id).not.toBe(+ oidcConnectedAccountId,+ );+ } finally {+ await deleteConnectedAccount(oidcConnectedAccountId);+ }+ });+it('falls back to an account shared with the whole workspace', async () => {+ const { visibility } = await readConnectedAccountState(+ JONY_CONNECTED_ACCOUNT_ID,+ );+await setVisibility(JONY_CONNECTED_ACCOUNT_ID, 'workspace');try {- const result = await service.composeEmail(baseParams, {- workspaceId: WORKSPACE_ID,- userWorkspaceId: UNKNOWN_USER_WORKSPACE_ID,+ const result = await service.composeEmail({+ parameters: baseParams,+ context: {+ workspaceId: WORKSPACE_ID,+ userWorkspaceId: UNKNOWN_USER_WORKSPACE_ID,+ },+ operation: EmailOperation.SEND,});expect(result.success).toBe(true);@@ -127,25 +372,31 @@ describe('EmailComposerService connected account resolution (integration)', () =JONY_CONNECTED_ACCOUNT_ID,);} finally {- await setVisibility(JONY_CONNECTED_ACCOUNT_ID, 'user');+ await setVisibility(JONY_CONNECTED_ACCOUNT_ID, visibility);}});it('throws rather than composing from a colleague account', async () => {await expect(- service.composeEmail(baseParams, {- workspaceId: WORKSPACE_ID,- userWorkspaceId: UNKNOWN_USER_WORKSPACE_ID,+ service.composeEmail({+ parameters: baseParams,+ context: {+ workspaceId: WORKSPACE_ID,+ userWorkspaceId: UNKNOWN_USER_WORKSPACE_ID,+ },+ operation: EmailOperation.SEND,}),- ).rejects.toThrow('No connected account available for user workspace');+ ).rejects.toThrow('available for user workspace');});it('takes the first workspace account when there is no caller (workflow run)', async () => {const firstWorkspaceConnectedAccountId =await getFirstWorkspaceConnectedAccountId();- const result = await service.composeEmail(baseParams, {- workspaceId: WORKSPACE_ID,+ const result = await service.composeEmail({+ parameters: baseParams,+ context: { workspaceId: WORKSPACE_ID },+ operation: EmailOperation.SEND,});expect(result.success).toBe(true);diff --git a/packages/twenty-shared/src/constants/EmailDraftingProviders.ts b/packages/twenty-shared/src/constants/EmailDraftingProviders.tsnew file mode 100644index 00000000000..a37550ed67e--- /dev/null+++ b/packages/twenty-shared/src/constants/EmailDraftingProviders.ts@@ -0,0 +1,7 @@+import { ConnectedAccountProvider } from '@/types';++export const EMAIL_DRAFTING_PROVIDERS: ConnectedAccountProvider[] = [+ ConnectedAccountProvider.GOOGLE,+ ConnectedAccountProvider.MICROSOFT,+ ConnectedAccountProvider.IMAP_SMTP_CALDAV,+];diff --git a/packages/twenty-shared/src/constants/EmailSendingProviders.ts b/packages/twenty-shared/src/constants/EmailSendingProviders.tsnew file mode 100644index 00000000000..76e30146120--- /dev/null+++ b/packages/twenty-shared/src/constants/EmailSendingProviders.ts@@ -0,0 +1,8 @@+import { ConnectedAccountProvider } from '@/types';++export const EMAIL_SENDING_PROVIDERS: ConnectedAccountProvider[] = [+ ConnectedAccountProvider.GOOGLE,+ ConnectedAccountProvider.MICROSOFT,+ ConnectedAccountProvider.IMAP_SMTP_CALDAV,+ ConnectedAccountProvider.EMAIL_GROUP,+];diff --git a/packages/twenty-shared/src/constants/index.ts b/packages/twenty-shared/src/constants/index.tsindex b47366d62bc..ee3f65b5c35 100644--- a/packages/twenty-shared/src/constants/index.ts+++ b/packages/twenty-shared/src/constants/index.ts@@ -28,7 +28,9 @@ export type { DocumentationPath } from './DocumentationPaths';export { DOCUMENTATION_PATHS } from './DocumentationPaths';export type { DocumentationSupportedLanguage } from './DocumentationSupportedLanguages';export { DOCUMENTATION_SUPPORTED_LANGUAGES } from './DocumentationSupportedLanguages';+export { EMAIL_DRAFTING_PROVIDERS } from './EmailDraftingProviders';export { EMAIL_IMAGE_MIME_TYPES } from './EmailImageMimeTypes';+export { EMAIL_SENDING_PROVIDERS } from './EmailSendingProviders';export type { EnterpriseInstanceType } from './EnterpriseInstanceType';export { ENTERPRISE_INSTANCE_TYPE } from './EnterpriseInstanceType';export { EVERYONE_PRINCIPAL_ID } from './EveryonePrincipalId';diff --git a/packages/twenty-shared/src/types/ConnectedAccountEmailFields.ts b/packages/twenty-shared/src/types/ConnectedAccountEmailFields.tsnew file mode 100644index 00000000000..511d79a6783--- /dev/null+++ b/packages/twenty-shared/src/types/ConnectedAccountEmailFields.ts@@ -0,0 +1,9 @@+import {+ type ConnectedAccountProvider,+ type EmailConnectionParameters,+} from '@/types';++export type ConnectedAccountEmailFields = {+ provider: ConnectedAccountProvider;+ connectionParameters?: EmailConnectionParameters | null;+};diff --git a/packages/twenty-shared/src/types/EmailConnectionParameters.ts b/packages/twenty-shared/src/types/EmailConnectionParameters.tsnew file mode 100644index 00000000000..0d6ee2eec12--- /dev/null+++ b/packages/twenty-shared/src/types/EmailConnectionParameters.ts@@ -0,0 +1,5 @@+export type EmailConnectionParameters = {+ IMAP?: object;+ SMTP?: object;+ CALDAV?: object;+};diff --git a/packages/twenty-shared/src/types/EmailOperation.ts b/packages/twenty-shared/src/types/EmailOperation.tsnew file mode 100644index 00000000000..d744912f82f--- /dev/null+++ b/packages/twenty-shared/src/types/EmailOperation.ts@@ -0,0 +1,4 @@+export enum EmailOperation {+ SEND = 'SEND',+ DRAFT = 'DRAFT',+}diff --git a/packages/twenty-shared/src/types/index.ts b/packages/twenty-shared/src/types/index.tsindex bc4fe196e8f..81dec7ac0ae 100644--- a/packages/twenty-shared/src/types/index.ts+++ b/packages/twenty-shared/src/types/index.ts@@ -69,11 +69,14 @@ export {export type { CompositeFieldSubFieldName } from './CompositeFieldSubFieldNameType';export type { ConfigVariableValue } from './ConfigVariableValue';export type { ConfirmationModalCaller } from './ConfirmationModalCaller';+export type { ConnectedAccountEmailFields } from './ConnectedAccountEmailFields';export { ConnectedAccountProvider } from './ConnectedAccountProvider';export { ContextStorePageType } from './ContextStorePageType';export { CoreObjectNameSingular } from './CoreObjectNameSingular';export { CrudOperationType } from './CrudOperationType';export type { EmailAttachment } from './EmailAttachment';+export type { EmailConnectionParameters } from './EmailConnectionParameters';+export { EmailOperation } from './EmailOperation';export type { EmptyObject } from './EmptyObject.type';export type {SnackBarVariant,diff --git a/packages/twenty-shared/src/utils/email/__tests__/canConnectedAccountPerformEmailOperation.test.ts b/packages/twenty-shared/src/utils/email/__tests__/canConnectedAccountPerformEmailOperation.test.tsnew file mode 100644index 00000000000..ca1d58912f5--- /dev/null+++ b/packages/twenty-shared/src/utils/email/__tests__/canConnectedAccountPerformEmailOperation.test.ts@@ -0,0 +1,171 @@+import { ConnectedAccountProvider, EmailOperation } from '@/types';+import { canConnectedAccountPerformEmailOperation } from '@/utils/email/canConnectedAccountPerformEmailOperation';++const connectionParameters = { host: 'mail.example.com', port: 993 };++describe('canConnectedAccountPerformEmailOperation', () => {+ describe('IMAP_SMTP_CALDAV, where capability depends on what is configured', () => {+ it('sends but cannot draft when only SMTP is configured', () => {+ const connectedAccount = {+ provider: ConnectedAccountProvider.IMAP_SMTP_CALDAV,+ connectionParameters: { SMTP: connectionParameters },+ };++ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.SEND,+ }),+ ).toBe(true);+ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.DRAFT,+ }),+ ).toBe(false);+ });++ it('drafts but cannot send when only IMAP is configured', () => {+ const connectedAccount = {+ provider: ConnectedAccountProvider.IMAP_SMTP_CALDAV,+ connectionParameters: { IMAP: connectionParameters },+ };++ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.SEND,+ }),+ ).toBe(false);+ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.DRAFT,+ }),+ ).toBe(true);+ });++ it('does both when IMAP and SMTP are configured', () => {+ const connectedAccount = {+ provider: ConnectedAccountProvider.IMAP_SMTP_CALDAV,+ connectionParameters: {+ IMAP: connectionParameters,+ SMTP: connectionParameters,+ },+ };++ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.SEND,+ }),+ ).toBe(true);+ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.DRAFT,+ }),+ ).toBe(true);+ });++ it('does neither when connection parameters are missing entirely', () => {+ const connectedAccount = {+ provider: ConnectedAccountProvider.IMAP_SMTP_CALDAV,+ connectionParameters: null,+ };++ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.SEND,+ }),+ ).toBe(false);+ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.DRAFT,+ }),+ ).toBe(false);+ });++ it('does neither when neither IMAP nor SMTP is configured', () => {+ const connectedAccount = {+ provider: ConnectedAccountProvider.IMAP_SMTP_CALDAV,+ connectionParameters: {},+ };++ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.SEND,+ }),+ ).toBe(false);+ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.DRAFT,+ }),+ ).toBe(false);+ });+ });++ describe('providers whose capability does not depend on configuration', () => {+ it('lets Google send and draft', () => {+ const connectedAccount = {+ provider: ConnectedAccountProvider.GOOGLE,+ connectionParameters: null,+ };++ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.SEND,+ }),+ ).toBe(true);+ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.DRAFT,+ }),+ ).toBe(true);+ });++ it('lets an email group send but never draft', () => {+ const connectedAccount = {+ provider: ConnectedAccountProvider.EMAIL_GROUP,+ connectionParameters: null,+ };++ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.SEND,+ }),+ ).toBe(true);+ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount,+ operation: EmailOperation.DRAFT,+ }),+ ).toBe(false);+ });++ it('refuses a provider absent from both allowlists even with SMTP configured', () => {+ for (const provider of [+ ConnectedAccountProvider.OIDC,+ ConnectedAccountProvider.SAML,+ ConnectedAccountProvider.APP,+ ]) {+ expect(+ canConnectedAccountPerformEmailOperation({+ connectedAccount: {+ provider,+ connectionParameters: { SMTP: connectionParameters },+ },+ operation: EmailOperation.SEND,+ }),+ ).toBe(false);+ }+ });+ });+});diff --git a/packages/twenty-shared/src/utils/email/canConnectedAccountPerformEmailOperation.ts b/packages/twenty-shared/src/utils/email/canConnectedAccountPerformEmailOperation.tsnew file mode 100644index 00000000000..c3b91fe5416--- /dev/null+++ b/packages/twenty-shared/src/utils/email/canConnectedAccountPerformEmailOperation.ts@@ -0,0 +1,38 @@+import {+ ConnectedAccountProvider,+ type ConnectedAccountEmailFields,+ EmailOperation,+} from '@/types';+import { assertUnreachable } from '@/utils/assertUnreachable';+import { getEmailProvidersForOperation } from '@/utils/email/getEmailProvidersForOperation';+import { isDefined } from '@/utils/validation/isDefined';++export const canConnectedAccountPerformEmailOperation = ({+ connectedAccount,+ operation,+}: {+ connectedAccount: ConnectedAccountEmailFields;+ operation: EmailOperation;+}): boolean => {+ const { provider, connectionParameters } = connectedAccount;++ if (!getEmailProvidersForOperation(operation).includes(provider)) {+ return false;+ }++ if (provider !== ConnectedAccountProvider.IMAP_SMTP_CALDAV) {+ return true;+ }++ switch (operation) {+ case EmailOperation.SEND:+ return isDefined(connectionParameters?.SMTP);+ case EmailOperation.DRAFT:+ return isDefined(connectionParameters?.IMAP);+ default:+ return assertUnreachable(+ operation,+ `Unhandled email operation: ${operation}`,+ );+ }+};diff --git a/packages/twenty-shared/src/utils/email/getEmailProvidersForOperation.ts b/packages/twenty-shared/src/utils/email/getEmailProvidersForOperation.tsnew file mode 100644index 00000000000..b5b3a6b9ed0--- /dev/null+++ b/packages/twenty-shared/src/utils/email/getEmailProvidersForOperation.ts@@ -0,0 +1,19 @@+import { EMAIL_DRAFTING_PROVIDERS, EMAIL_SENDING_PROVIDERS } from '@/constants';+import { type ConnectedAccountProvider, EmailOperation } from '@/types';+import { assertUnreachable } from '@/utils/assertUnreachable';++export const getEmailProvidersForOperation = (+ operation: EmailOperation,+): ConnectedAccountProvider[] => {+ switch (operation) {+ case EmailOperation.SEND:+ return EMAIL_SENDING_PROVIDERS;+ case EmailOperation.DRAFT:+ return EMAIL_DRAFTING_PROVIDERS;+ default:+ return assertUnreachable(+ operation,+ `Unhandled email operation: ${operation}`,+ );+ }+};diff --git a/packages/twenty-shared/src/utils/index.ts b/packages/twenty-shared/src/utils/index.tsindex 9da32c8920f..085bc3b2b5d 100644--- a/packages/twenty-shared/src/utils/index.ts+++ b/packages/twenty-shared/src/utils/index.ts@@ -50,7 +50,9 @@ export { turnJSDateToPlainDate } from './date/turnJSDateToPlainDate';export { turnPlainDateIntoUserTimeZoneInstantString } from './date/turnPlainDateIntoUserTimeZoneInstantString';export { turnPlainDateToShiftedDateInSystemTimeZone } from './date/turnPlainDateToShiftedDateInSystemTimeZone';export { deepMerge } from './deepMerge';+export { canConnectedAccountPerformEmailOperation } from './email/canConnectedAccountPerformEmailOperation';export { formatEmailAddress } from './email/formatEmailAddress';+export { getEmailProvidersForOperation } from './email/getEmailProvidersForOperation';export { getSendableEmailHandles } from './email/getSendableEmailHandles';export type { ParsedEmailAddress } from './email/parseEmailAddressList';export { parseEmailAddressList } from './email/parseEmailAddressList';