The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
messaging: Allow sending outbound mail from a verified account alias (#24560)
neo773f09c89a2693e
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex e4d0c6e0758..3a1ffc96ec2 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -4999,6 +4999,7 @@ input CreateCalendarEventInput {input SendEmailInput {connectedAccountId: String!+ fromHandle: Stringto: String!cc: Stringbcc: Stringdiff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex 7df71906fbd..ad698f72703 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -7139,7 +7139,7 @@ export interface EditSsoInput {id: Scalars['UUID'],status: SSOIdentityProviderStexport interface CreateCalendarEventInput {connectedAccountId: Scalars['String'],title: Scalars['String'],description?: (Scalars['String'] | null),location?: (Scalars['String'] | null),startsAt: Scalars['String'],endsAt: Scalars['String'],isFullDay?: (Scalars['Boolean'] | null),timeZone?: (Scalars['String'] | null),attendees?: (Scalars['String'] | null),sendInvitations?: (Scalars['Boolean'] | null),addConferencing?: (Scalars['Boolean'] | null)}-export interface SendEmailInput {connectedAccountId: Scalars['String'],to: Scalars['String'],cc?: (Scalars['String'] | null),bcc?: (Scalars['String'] | null),subject: Scalars['String'],body: Scalars['String'],inReplyTo?: (Scalars['String'] | null),draftMessageId?: (Scalars['String'] | null),files?: (SendEmailAttachmentInput[] | null)}+export interface SendEmailInput {connectedAccountId: Scalars['String'],fromHandle?: (Scalars['String'] | null),to: Scalars['String'],cc?: (Scalars['String'] | null),bcc?: (Scalars['String'] | null),subject: Scalars['String'],body: Scalars['String'],inReplyTo?: (Scalars['String'] | null),draftMessageId?: (Scalars['String'] | null),files?: (SendEmailAttachmentInput[] | null)}export interface SendEmailAttachmentInput {id: Scalars['String'],name: Scalars['String']}diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex b2a2c7e4f87..9df94717f9f 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -12713,6 +12713,9 @@ export default {"connectedAccountId": [1],+ "fromHandle": [+ 1+ ],"to": [1],diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 223bd697f52..e9831c79446 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -5391,6 +5391,7 @@ export type SendEmailInput = {connectedAccountId: Scalars['String']['input'];draftMessageId?: InputMaybe<Scalars['String']['input']>;files?: InputMaybe<Array<SendEmailAttachmentInput>>;+ fromHandle?: InputMaybe<Scalars['String']['input']>;inReplyTo?: InputMaybe<Scalars['String']['input']>;subject: Scalars['String']['input'];to: Scalars['String']['input'];diff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.tsindex 5362b698656..25abb7e5f4a 100644--- a/packages/twenty-front/src/generated/graphql.ts+++ b/packages/twenty-front/src/generated/graphql.ts@@ -44,6 +44,7 @@ export type ComputeStepOutputSchemaInput = {export type ConnectedAccountHandleDto = {__typename?: 'ConnectedAccountHandleDTO';handle: Scalars['String']['output'];+ handleAliases?: Maybe<Array<Scalars['String']['output']>>;id: Scalars['UUID']['output'];provider: Scalars['String']['output'];};@@ -964,7 +965,7 @@ export type WorkflowStepConnectedAccountHandleQueryVariables = Exact<{}>;-export type WorkflowStepConnectedAccountHandleQuery = { __typename?: 'Query', workflowStepConnectedAccountHandle?: { __typename?: 'ConnectedAccountHandleDTO', id: any, handle: string, provider: string } | null };+export type WorkflowStepConnectedAccountHandleQuery = { __typename?: 'Query', workflowStepConnectedAccountHandle?: { __typename?: 'ConnectedAccountHandleDTO', id: any, handle: string, provider: string, handleAliases?: Array<string> | null } | null };export type SubmitFormStepMutationVariables = Exact<{input: SubmitFormStepInput;@@ -1022,7 +1023,7 @@ export const StopWorkflowRunDocument = {"kind":"Document","definitions":[{"kind"export const UpdateWorkflowRunStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkflowRunStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkflowRunStepInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkflowRunStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"settings"}},{"kind":"Field","name":{"kind":"Name","value":"valid"}},{"kind":"Field","name":{"kind":"Name","value":"nextStepIds"}},{"kind":"Field","name":{"kind":"Name","value":"position"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"x"}},{"kind":"Field","name":{"kind":"Name","value":"y"}}]}}]}}]}}]} as unknown as DocumentNode<UpdateWorkflowRunStepMutation, UpdateWorkflowRunStepMutationVariables>;export const UpdateWorkflowVersionStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkflowVersionStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkflowVersionStepInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkflowVersionStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"settings"}},{"kind":"Field","name":{"kind":"Name","value":"valid"}},{"kind":"Field","name":{"kind":"Name","value":"nextStepIds"}},{"kind":"Field","name":{"kind":"Name","value":"position"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"x"}},{"kind":"Field","name":{"kind":"Name","value":"y"}}]}}]}}]}}]} as unknown as DocumentNode<UpdateWorkflowVersionStepMutation, UpdateWorkflowVersionStepMutationVariables>;export const UpdateWorkflowVersionTriggerDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkflowVersionTrigger"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkflowVersionTriggerInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkflowVersionTrigger"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"trigger"}}]}}]}}]} as unknown as DocumentNode<UpdateWorkflowVersionTriggerMutation, UpdateWorkflowVersionTriggerMutationVariables>;-export const WorkflowStepConnectedAccountHandleDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkflowStepConnectedAccountHandle"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workflowStepConnectedAccountHandle"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"connectedAccountId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"provider"}}]}}]}}]} as unknown as DocumentNode<WorkflowStepConnectedAccountHandleQuery, WorkflowStepConnectedAccountHandleQueryVariables>;+export const WorkflowStepConnectedAccountHandleDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkflowStepConnectedAccountHandle"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workflowStepConnectedAccountHandle"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"connectedAccountId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"provider"}},{"kind":"Field","name":{"kind":"Name","value":"handleAliases"}}]}}]}}]} as unknown as DocumentNode<WorkflowStepConnectedAccountHandleQuery, WorkflowStepConnectedAccountHandleQueryVariables>;export const SubmitFormStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SubmitFormStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SubmitFormStepInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"submitFormStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<SubmitFormStepMutation, SubmitFormStepMutationVariables>;export const TestHttpRequestDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"TestHttpRequest"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"TestHttpRequestInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"testHttpRequest"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"success"}},{"kind":"Field","name":{"kind":"Name","value":"message"}},{"kind":"Field","name":{"kind":"Name","value":"result"}},{"kind":"Field","name":{"kind":"Name","value":"error"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"statusText"}},{"kind":"Field","name":{"kind":"Name","value":"headers"}}]}}]}}]} as unknown as DocumentNode<TestHttpRequestMutation, TestHttpRequestMutationVariables>;export const UpdateWorkflowVersionPositionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkflowVersionPositions"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkflowVersionPositionsInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkflowVersionPositions"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<UpdateWorkflowVersionPositionsMutation, UpdateWorkflowVersionPositionsMutationVariables>;diff --git a/packages/twenty-front/src/modules/accounts/types/ConnectedAccountSender.ts b/packages/twenty-front/src/modules/accounts/types/ConnectedAccountSender.tsnew file mode 100644index 00000000000..7fe7d6d8b20--- /dev/null+++ b/packages/twenty-front/src/modules/accounts/types/ConnectedAccountSender.ts@@ -0,0 +1,4 @@+export type ConnectedAccountSender = {+ connectedAccountId: string;+ fromHandle?: string;+};diff --git a/packages/twenty-front/src/modules/accounts/utils/buildConnectedAccountSenderOptions.ts b/packages/twenty-front/src/modules/accounts/utils/buildConnectedAccountSenderOptions.tsnew file mode 100644index 00000000000..2e21c76dab5--- /dev/null+++ b/packages/twenty-front/src/modules/accounts/utils/buildConnectedAccountSenderOptions.ts@@ -0,0 +1,16 @@+import { type ConnectedAccount } from '@/accounts/types/ConnectedAccount';+import { getSendableEmailHandles } from 'twenty-shared/utils';+import { type SelectOption } from 'twenty-ui/input';++export const buildConnectedAccountSenderOptions = (+ accounts: Pick<ConnectedAccount, 'handle' | 'handleAliases'>[],+): SelectOption<string>[] => {+ const handles = accounts.flatMap((account) =>+ getSendableEmailHandles(account),+ );++ return [...new Set(handles)].map((handle) => ({+ label: handle,+ value: handle,+ }));+};diff --git a/packages/twenty-front/src/modules/accounts/utils/canConnectedAccountSendEmail.ts b/packages/twenty-front/src/modules/accounts/utils/canConnectedAccountSendEmail.tsnew file mode 100644index 00000000000..c661b4c1c6d--- /dev/null+++ b/packages/twenty-front/src/modules/accounts/utils/canConnectedAccountSendEmail.ts@@ -0,0 +1,9 @@+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 e581ec9ccb5..f4337cbd765 100644--- a/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx+++ b/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx@@ -3,9 +3,8 @@ import { useContext } from 'react';import { DragDropProvider } from '@dnd-kit/react';import { styled } from '@linaria/react';import { t } from '@lingui/core/macro';-import { isDefined } from 'twenty-shared/utils';+import { getSendableEmailHandles, isDefined } from 'twenty-shared/utils';import { IconPaperclip } from 'twenty-ui/icon';-import { type SelectOption } from 'twenty-ui/input';import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';import { ComposerFieldRow } from '@/activities/components/ComposerFieldRow';@@ -22,6 +21,9 @@ import { type EmailRecipientsFieldId } from '@/activities/emails/recipients/typeimport { getEmailRecipientKey } from '@/activities/emails/recipients/utils/getEmailRecipientKey';import { type EmailRecipientsByFieldId } from '@/activities/emails/recipients/utils/moveEmailRecipientsBetweenFields';import { 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';@@ -112,16 +114,41 @@ export const EmailComposerFields = ({const { theme } = useContext(ThemeContext);const { uploadEmailImage } = useUploadEmailImage();const { data: accountsData } = useQuery<{- myConnectedAccounts: { id: string; handle: string }[];+ myConnectedAccounts: Pick<+ ConnectedAccount,+ 'id' | 'handle' | 'handleAliases' | 'provider' | 'connectionParameters'+ >[];}>(GET_MY_CONNECTED_ACCOUNTS);- const accountOptions: SelectOption<string>[] =- accountsData?.myConnectedAccounts?.map((account) => ({- label: account.handle,- value: account.id,- })) ?? [];+ const sendableAccounts = (accountsData?.myConnectedAccounts ?? []).filter(+ canConnectedAccountSendEmail,+ );++ const senderOptions = buildConnectedAccountSenderOptions(sendableAccounts);++ const hasMultipleSenders = senderOptions.length > 1;++ const selectedAccount = sendableAccounts.find(+ (account) => account.id === composerState.connectedAccountId,+ );++ const selectedSenderValue =+ composerState.fromHandle ?? selectedAccount?.handle;- const hasMultipleAccounts = accountOptions.length > 1;+ const handleSenderChange = (handle: string) => {+ const senderAccount = sendableAccounts.find((account) =>+ getSendableEmailHandles(account).includes(handle),+ );++ if (!isDefined(senderAccount)) {+ return;+ }++ composerState.setSender({+ connectedAccountId: senderAccount.id,+ fromHandle: handle,+ });+ };const allRecipientKeys = [...composerState.to,@@ -174,16 +201,14 @@ export const EmailComposerFields = ({onDragEnd={handlers.onDragEnd}><ComposerHeader>- {hasMultipleAccounts && (+ {hasMultipleSenders && (<ComposerFieldRow label={t`From`}><SelectdropdownId="email-composer-from-account"fullWidth- value={composerState.connectedAccountId}- options={accountOptions}- onChange={(value) =>- composerState.setConnectedAccountId(value)- }+ value={selectedSenderValue}+ options={senderOptions}+ onChange={handleSenderChange}/></ComposerFieldRow>)}diff --git a/packages/twenty-front/src/modules/activities/emails/hooks/__tests__/useEmailComposerState.test.tsx b/packages/twenty-front/src/modules/activities/emails/hooks/__tests__/useEmailComposerState.test.tsxnew file mode 100644index 00000000000..9e0d2008ec7--- /dev/null+++ b/packages/twenty-front/src/modules/activities/emails/hooks/__tests__/useEmailComposerState.test.tsx@@ -0,0 +1,151 @@+import { MockedProvider } from '@apollo/client/testing/react';+import { act, renderHook } from '@testing-library/react';+import { type ReactNode } from 'react';++import { SEND_EMAIL } from '@/activities/emails/graphql/mutations/sendEmail';+import { useEmailComposerState } from '@/activities/emails/hooks/useEmailComposerState';++const mockEnqueueSuccessSnackBar = jest.fn();+const mockEnqueueErrorSnackBar = jest.fn();++jest.mock('@/ui/feedback/snack-bar-manager/hooks/useSnackBar', () => ({+ useSnackBar: () => ({+ enqueueSuccessSnackBar: mockEnqueueSuccessSnackBar,+ enqueueErrorSnackBar: mockEnqueueErrorSnackBar,+ }),+}));++jest.mock('@/object-metadata/hooks/useApolloCoreClient', () => ({+ useApolloCoreClient: () => ({ refetchQueries: jest.fn() }),+}));++const createSendEmailMock = (input: {+ connectedAccountId: string;+ fromHandle?: string;+}) => ({+ request: {+ query: SEND_EMAIL,+ variables: {+ input: {+ to: '[email protected]',+ cc: undefined,+ bcc: undefined,+ subject: 'Hello',+ body: '',+ inReplyTo: undefined,+ draftMessageId: undefined,+ files: undefined,+ ...input,+ },+ },+ },+ result: {+ data: {+ sendEmail: {+ success: true,+ error: null,+ messageThreadId: 'message-thread-1',+ },+ },+ },+});++const renderComposerState = (+ mocks: ReturnType<typeof createSendEmailMock>[],+ onSent: (messageThreadId: string | null) => void,+) =>+ renderHook(+ () =>+ useEmailComposerState({+ connectedAccountId: 'account-1',+ defaultTo: '[email protected]',+ defaultSubject: 'Hello',+ onSent,+ }),+ {+ wrapper: ({ children }: { children: ReactNode }) => (+ <MockedProvider mocks={mocks}>{children}</MockedProvider>+ ),+ },+ );++describe('useEmailComposerState', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it('sends from the connected account when no alias was picked', async () => {+ const onSent = jest.fn();++ const { result } = renderComposerState(+ [+ createSendEmailMock({+ connectedAccountId: 'account-1',+ fromHandle: undefined,+ }),+ ],+ onSent,+ );++ await act(async () => {+ await result.current.handleSend();+ });++ expect(onSent).toHaveBeenCalledWith('message-thread-1');+ });++ it('sends from the picked alias together with the account owning it', async () => {+ const onSent = jest.fn();++ const { result } = renderComposerState(+ [+ createSendEmailMock({+ connectedAccountId: 'account-2',+ fromHandle: '[email protected]',+ }),+ ],+ onSent,+ );++ act(() => {+ result.current.setSender({+ connectedAccountId: 'account-2',+ fromHandle: '[email protected]',+ });+ });++ await act(async () => {+ await result.current.handleSend();+ });++ expect(onSent).toHaveBeenCalledWith('message-thread-1');+ expect(mockEnqueueErrorSnackBar).not.toHaveBeenCalled();+ });++ it('drops a picked alias when the reply moves to another account', () => {+ const { result, rerender } = renderHook(+ ({ connectedAccountId }: { connectedAccountId: string }) =>+ useEmailComposerState({ connectedAccountId }),+ {+ initialProps: { connectedAccountId: 'account-1' },+ wrapper: ({ children }: { children: ReactNode }) => (+ <MockedProvider mocks={[]}>{children}</MockedProvider>+ ),+ },+ );++ act(() => {+ result.current.setSender({+ connectedAccountId: 'account-1',+ fromHandle: '[email protected]',+ });+ });++ expect(result.current.fromHandle).toBe('[email protected]');++ rerender({ connectedAccountId: 'account-2' });++ expect(result.current.connectedAccountId).toBe('account-2');+ expect(result.current.fromHandle).toBeUndefined();+ });+});diff --git a/packages/twenty-front/src/modules/activities/emails/hooks/useEmailComposerState.ts b/packages/twenty-front/src/modules/activities/emails/hooks/useEmailComposerState.tsindex a444c7654e3..ec15864c77e 100644--- a/packages/twenty-front/src/modules/activities/emails/hooks/useEmailComposerState.ts+++ b/packages/twenty-front/src/modules/activities/emails/hooks/useEmailComposerState.ts@@ -7,6 +7,7 @@ import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailRimport { isValidEmailRecipientAddress } from '@/activities/emails/recipients/utils/isValidEmailRecipientAddress';import { parseEmailRecipients } from '@/activities/emails/recipients/utils/parseEmailRecipients';import { serializeEmailRecipients } from '@/activities/emails/recipients/utils/serializeEmailRecipients';+import { type ConnectedAccountSender } from '@/accounts/types/ConnectedAccountSender';import { type EmailDraftPrefill } from '@/activities/emails/types/EmailDraftPrefill';type UseEmailComposerStateArgs = {@@ -37,9 +38,19 @@ export const useEmailComposerState = ({const initialSubject = draftPrefill?.subject ?? defaultSubject;const initialBody = draftPrefill?.body ?? '';- const [connectedAccountId, setConnectedAccountId] = useState(+ const [sender, setSender] = useState<ConnectedAccountSender>({+ connectedAccountId: initialConnectedAccountId,+ });+ const [previousConnectedAccountId, setPreviousConnectedAccountId] = useState(initialConnectedAccountId,);++ if (previousConnectedAccountId !== initialConnectedAccountId) {+ setPreviousConnectedAccountId(initialConnectedAccountId);+ setSender({ connectedAccountId: initialConnectedAccountId });+ }++ const { connectedAccountId, fromHandle } = sender;const [to, setTo] = useState<EmailRecipient[]>(() =>parseEmailRecipients(initialTo),);@@ -87,6 +98,7 @@ export const useEmailComposerState = ({const { success, messageThreadId } = await sendEmail({connectedAccountId,+ fromHandle,to: serializeEmailRecipients(to),cc: serializedCc || undefined,bcc: serializedBcc || undefined,@@ -103,6 +115,7 @@ export const useEmailComposerState = ({}, [canSend,connectedAccountId,+ fromHandle,to,cc,bcc,@@ -117,7 +130,8 @@ export const useEmailComposerState = ({return {connectedAccountId,- setConnectedAccountId,+ fromHandle,+ setSender,to,setTo,cc,diff --git a/packages/twenty-front/src/modules/activities/emails/hooks/useSendEmail.ts b/packages/twenty-front/src/modules/activities/emails/hooks/useSendEmail.tsindex fb272d52fbc..226614741c8 100644--- a/packages/twenty-front/src/modules/activities/emails/hooks/useSendEmail.ts+++ b/packages/twenty-front/src/modules/activities/emails/hooks/useSendEmail.ts@@ -19,6 +19,7 @@ type SendEmailResult = {type SendEmailParams = {connectedAccountId: string;+ fromHandle?: string;to: string;cc?: string;bcc?: string;@@ -46,6 +47,7 @@ export const useSendEmail = () => {variables: {input: {connectedAccountId: params.connectedAccountId,+ fromHandle: params.fromHandle,to: params.to,cc: params.cc,bcc: params.bcc,diff --git a/packages/twenty-front/src/modules/workflow/graphql/queries/workflowStepConnectedAccountHandle.ts b/packages/twenty-front/src/modules/workflow/graphql/queries/workflowStepConnectedAccountHandle.tsindex 164fa0e60f2..544304130da 100644--- a/packages/twenty-front/src/modules/workflow/graphql/queries/workflowStepConnectedAccountHandle.ts+++ b/packages/twenty-front/src/modules/workflow/graphql/queries/workflowStepConnectedAccountHandle.ts@@ -8,6 +8,7 @@ export const WORKFLOW_STEP_CONNECTED_ACCOUNT_HANDLE = gql`idhandleprovider+ handleAliases}}`;diff --git a/packages/twenty-front/src/modules/workflow/types/EmailFormData.ts b/packages/twenty-front/src/modules/workflow/types/EmailFormData.tsindex b1db7f49615..7b235f2f250 100644--- a/packages/twenty-front/src/modules/workflow/types/EmailFormData.ts+++ b/packages/twenty-front/src/modules/workflow/types/EmailFormData.ts@@ -5,6 +5,7 @@ import {export type EmailFormData = {connectedAccountId: string;+ fromHandle: string;recipients: Required<EmailRecipients>;subject: string;body: string;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 0af7417067d..6a0cd61566f 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,4 +1,6 @@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';@@ -29,10 +31,11 @@ import { useQuery } from '@apollo/client/react';import { t } from '@lingui/core/macro';import { useEffect, useState } from 'react';import { ConnectedAccountProvider, SettingsPath } from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';+import { getSendableEmailHandles, isDefined } from 'twenty-shared/utils';import { Callout } from 'twenty-ui/feedback';import { IconPlus } from 'twenty-ui/icon';-import { Button, type SelectOption } from 'twenty-ui/input';+import { isNonEmptyString } from '@sniptt/guards';+import { Button } from 'twenty-ui/input';import { MenuItem } from 'twenty-ui/navigation';import { useNavigateSettings } from '~/hooks/useNavigateSettings';@@ -62,14 +65,15 @@ export const WorkflowEditActionEmailBase = ({const redirectUrl = `/object/workflow/${workflowVisualizerWorkflowId}`;- const { formData, handleFieldChange, saveAction } = useEmailForm({- action,- onActionUpdate:- actionOptions.readonly === true- ? undefined- : actionOptions.onActionUpdate,- readonly: actionOptions.readonly === true,- });+ const { formData, handleFieldChange, handleFieldsChange, saveAction } =+ useEmailForm({+ action,+ onActionUpdate:+ actionOptions.readonly === true+ ? undefined+ : actionOptions.onActionUpdate,+ readonly: actionOptions.readonly === true,+ });const [visibleAdvancedFields, setVisibleAdvancedFields] = useState<{cc: boolean;@@ -105,10 +109,6 @@ export const WorkflowEditActionEmailBase = ({});};- const handleConnectedAccountChange = (connectedAccountId: string | null) => {- handleFieldChange('connectedAccountId', connectedAccountId);- };-const apolloCoreClient = useApolloCoreClient();const navigate = useNavigateSettings();@@ -127,7 +127,7 @@ export const WorkflowEditActionEmailBase = ({const { data: otherAccountData, loading: otherAccountLoading } = useQuery<{workflowStepConnectedAccountHandle: Pick<ConnectedAccount,- 'id' | 'handle' | 'provider'+ 'id' | 'handle' | 'provider' | 'handleAliases'> | null;}>(WORKFLOW_STEP_CONNECTED_ACCOUNT_HANDLE, {client: apolloCoreClient,@@ -163,28 +163,49 @@ export const WorkflowEditActionEmailBase = ({}: null;- const connectedAccountOptions: SelectOption<string>[] = [];+ const sendableAccounts = [+ ...myAccounts.filter(canConnectedAccountSendEmail),+ ...(isDefined(otherAccount) ? [otherAccount] : []),+ ];++ const senderOptions = buildConnectedAccountSenderOptions(sendableAccounts);++ const configuredAccount = ownAccount ?? otherAccount;++ const configuredSenderHandle = isNonEmptyString(formData.fromHandle)+ ? formData.fromHandle+ : configuredAccount?.handle;++ const selectedSenderValue = isSenderVariable+ ? configuredAccountId+ : configuredSenderHandle;++ const handleSenderChange = (senderValue: string | null) => {+ if (!isNonEmptyString(senderValue)) {+ handleFieldsChange({ connectedAccountId: '', fromHandle: '' });- myAccounts.forEach((account) => {- if (- account.provider === ConnectedAccountProvider.IMAP_SMTP_CALDAV &&- !isDefined(account.connectionParameters?.SMTP)- ) {return;}- connectedAccountOptions.push({- label: account.handle,- value: account.id,- });- });+ if (isStandaloneVariableString(senderValue)) {+ handleFieldsChange({ connectedAccountId: senderValue, fromHandle: '' });++ return;+ }++ const senderAccount = sendableAccounts.find((account) =>+ getSendableEmailHandles(account).includes(senderValue),+ );- if (isDefined(otherAccount)) {- connectedAccountOptions.push({- label: otherAccount.handle,- value: otherAccount.id,+ if (!isDefined(senderAccount)) {+ return;+ }++ handleFieldsChange({+ connectedAccountId: senderAccount.id,+ fromHandle: senderValue,});- }+ };useEffect(() => {return () => {@@ -197,12 +218,12 @@ export const WorkflowEditActionEmailBase = ({<><WorkflowStepBody><FormSelectFieldInput- key={`connected-account-${formData.connectedAccountId ?? 'none'}`}- label={t`Account`}- hint={t`Pick a connected account or set a workspace member as variable`}- defaultValue={formData.connectedAccountId}- options={connectedAccountOptions}- onChange={handleConnectedAccountChange}+ key={`sender-${selectedSenderValue ?? 'none'}`}+ label={t`From`}+ hint={t`Pick an address to send from or set a workspace member as variable`}+ defaultValue={selectedSenderValue}+ options={senderOptions}+ onChange={handleSenderChange}VariablePicker={WorkflowVariablePicker}readonly={actionOptions.readonly}callToActionButton={{diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowRunStepLogsEmailDetail.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowRunStepLogsEmailDetail.tsxindex 44dc0605d69..f8d5809f2d0 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowRunStepLogsEmailDetail.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowRunStepLogsEmailDetail.tsx@@ -1,5 +1,6 @@import { styled } from '@linaria/react';import { useLingui } from '@lingui/react/macro';+import { isNonEmptyString } from '@sniptt/guards';import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';import { type WorkflowRunStepLog } from 'twenty-shared/workflow';import {@@ -152,6 +153,12 @@ export const WorkflowRunStepLogsEmailDetail = ({<StyledSection><StyledSectionTitle>{t`Recipients`}</StyledSectionTitle><StyledRecipientsCard>+ {isNonEmptyString(details.fromHandle) && (+ <>+ <StyledRecipientLabel>{t`From`}</StyledRecipientLabel>+ <StyledRecipientValue>{details.fromHandle}</StyledRecipientValue>+ </>+ )}<StyledRecipientLabel>{t`To`}</StyledRecipientLabel><StyledRecipientValue>{isNonEmptyArray(details.recipients.to)diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/__stories__/WorkflowEditActionEmailBase.stories.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/__stories__/WorkflowEditActionEmailBase.stories.tsxindex d6eb3382e99..de9e56777db 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/__stories__/WorkflowEditActionEmailBase.stories.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/__stories__/WorkflowEditActionEmailBase.stories.tsx@@ -25,7 +25,7 @@ const mockedConnectedAccounts = [authFailedAt: null,archivedAt: null,scopes: ['email', 'calendar'],- handleAliases: '',+ handleAliases: ['[email protected]'],lastSignedInAt: null,userWorkspaceId: '20202020-0687-4c41-b707-ed1bfca972a7',connectionProviderId: null,@@ -246,7 +246,7 @@ export const Default: Story = {play: async ({ canvasElement }) => {const canvas = within(canvasElement);- expect(await canvas.findByText('Account')).toBeVisible();+ expect(await canvas.findByText('From')).toBeVisible();expect(await canvas.findByText('To')).toBeVisible();expect(await canvas.findByText('Subject')).toBeVisible();expect(await canvas.findByText('Body')).toBeVisible();@@ -264,7 +264,7 @@ export const Configured: Story = {play: async ({ canvasElement }) => {const canvas = within(canvasElement);- expect(await canvas.findByText('Account')).toBeVisible();+ expect(await canvas.findByText('From')).toBeVisible();expect(await canvas.findByText('To')).toBeVisible();const emailInput = await canvas.findByText('[email protected]');@@ -285,7 +285,7 @@ export const DraftEmail: Story = {play: async ({ canvasElement }) => {const canvas = within(canvasElement);- expect(await canvas.findByText('Account')).toBeVisible();+ expect(await canvas.findByText('From')).toBeVisible();expect(await canvas.findByText('To')).toBeVisible();expect(await canvas.findByText('Subject')).toBeVisible();expect(await canvas.findByText('Body')).toBeVisible();@@ -303,11 +303,11 @@ export const VariableSender: Story = {play: async ({ canvasElement }) => {const canvas = within(canvasElement);- expect(await canvas.findByText('Account')).toBeVisible();+ expect(await canvas.findByText('From')).toBeVisible();expect(await canvas.findByLabelText('Remove variable')).toBeInTheDocument();expect(await canvas.findByText(- 'Pick a connected account or set a workspace member as variable',+ 'Pick an address to send from or set a workspace member as variable',),).toBeVisible();},@@ -323,11 +323,11 @@ export const VariableSenderSendEmail: Story = {play: async ({ canvasElement }) => {const canvas = within(canvasElement);- expect(await canvas.findByText('Account')).toBeVisible();+ expect(await canvas.findByText('From')).toBeVisible();expect(await canvas.findByLabelText('Remove variable')).toBeInTheDocument();expect(await canvas.findByText(- 'Pick a connected account or set a workspace member as variable',+ 'Pick an address to send from or set a workspace member as variable',),).toBeVisible();},diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/hooks/useEmailForm.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/hooks/useEmailForm.tsindex 3cded844a47..c7dff3333d1 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/hooks/useEmailForm.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/hooks/useEmailForm.ts@@ -20,6 +20,7 @@ export const useEmailForm = ({return {connectedAccountId: action.settings.input.connectedAccountId,+ fromHandle: action.settings.input.fromHandle ?? '',recipients: {to: inputRecipients?.to ?? '',cc: inputRecipients?.cc ?? '',@@ -43,6 +44,7 @@ export const useEmailForm = ({...action.settings,input: {connectedAccountId: formData.connectedAccountId,+ fromHandle: formData.fromHandle,recipients: formData.recipients,subject: formData.subject,body: formData.body,@@ -53,22 +55,26 @@ export const useEmailForm = ({});}, 1_000);+ const applyFormData = (newFormData: EmailFormData) => {+ setFormData(newFormData);+ saveAction(newFormData);+ };++ const handleFieldsChange = (updatedFields: Partial<EmailFormData>) => {+ applyFormData({ ...formData, ...updatedFields });+ };+const handleFieldChange = (fieldName: keyof EmailFormData,updatedValue: JsonValue,) => {- const newFormData: EmailFormData = {- ...formData,- [fieldName]: updatedValue,- };-- setFormData(newFormData);- saveAction(newFormData);+ applyFormData({ ...formData, [fieldName]: updatedValue });};return {formData,handleFieldChange,+ handleFieldsChange,saveAction,};};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 0698866a194..2c52165bd45 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@@ -106,6 +106,7 @@ export class DraftEmailTool implements Tool {private async createDraft(data: ComposedEmail): Promise<void> {await this.messageOutboundService.createDraft({+ fromHandle: data.fromHandle,to: data.recipients.to,cc: data.recipients.cc.length > 0 ? data.recipients.cc : undefined,bcc: data.recipients.bcc.length > 0 ? data.recipients.bcc : undefined,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 1bb4315fa37..0e1318381d1 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@@ -338,7 +338,7 @@ export class EmailComposerService {context: ToolExecutionContext,): Promise<EmailComposerResult> {const { workspaceId, userWorkspaceId } = context;- const { subject, body, files, inReplyTo } = parameters;+ const { subject, body, files, inReplyTo, fromHandle } = parameters;let { connectedAccountId } = parameters;let recipients: { to: string[]; cc: string[]; bcc: string[] };@@ -440,6 +440,7 @@ export class EmailComposerService {sanitizedHtmlBody,attachments,connectedAccount,+ fromHandle,messageChannelId: messageChannel?.id,shouldPersistMessage: isDefined(messageChannel),inReplyTo,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 f20ffd65597..64ebc7b4744 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@@ -36,6 +36,12 @@ export const EmailToolInputZodSchema = z.object({'The UUID of the connected account to send the email from. Provide this only if you have it; otherwise, leave blank.',).optional(),+ fromHandle: z+ .string()+ .describe(+ 'The address to send from. Must be the connected account handle or one of its verified aliases. Leave blank to send from the connected account handle.',+ )+ .optional(),files: z.array(workflowFileSchema).describe('Array of file objects to attach to the email')diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/types/compose-email-params.type.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/types/compose-email-params.type.tsindex 255bcf7a8a2..48f993ba68f 100644--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/types/compose-email-params.type.ts+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/types/compose-email-params.type.ts@@ -10,6 +10,7 @@ export type ComposeEmailParams = {subject: string;body: string | EmailDocument;connectedAccountId?: string;+ fromHandle?: string;files?: Array<EmailAttachment>;inReplyTo?: string;};diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/types/composed-email.type.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/types/composed-email.type.tsindex 04851909713..bb28e936fba 100644--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/types/composed-email.type.ts+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/types/composed-email.type.ts@@ -9,6 +9,7 @@ export type ComposedEmail = {sanitizedHtmlBody: string;attachments: MessageAttachment[];connectedAccount: ConnectedAccountEntity;+ fromHandle?: string;messageChannelId?: string;shouldPersistMessage: boolean;inReplyTo?: string;diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.tsindex 93073022884..10375049655 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.ts@@ -73,6 +73,7 @@ export class WorkflowVersionStepResolver {id: account.id,handle: account.handle,provider: account.provider,+ handleAliases: account.handleAliases,};}diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/dtos/connected-account-handle.dto.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/dtos/connected-account-handle.dto.tsindex 25f9f483cbd..a7a831c47b2 100644--- a/packages/twenty-server/src/engine/metadata-modules/connected-account/dtos/connected-account-handle.dto.ts+++ b/packages/twenty-server/src/engine/metadata-modules/connected-account/dtos/connected-account-handle.dto.ts@@ -1,6 +1,12 @@import { Field, ObjectType } from '@nestjs/graphql';-import { IsNotEmpty, IsString, IsUUID } from 'class-validator';+import {+ IsArray,+ IsNotEmpty,+ IsOptional,+ IsString,+ IsUUID,+} from 'class-validator';import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';@@ -20,4 +26,10 @@ export class ConnectedAccountHandleDTO {@IsNotEmpty()@Field()provider: string;++ @IsArray()+ @IsString({ each: true })+ @IsOptional()+ @Field(() => [String], { nullable: true })+ handleAliases?: string[] | null;}diff --git a/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/gmail/services/gmail-message-outbound.service.ts b/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/gmail/services/gmail-message-outbound.service.tsindex a2ac3357492..fc504527125 100644--- a/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/gmail/services/gmail-message-outbound.service.ts+++ b/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/gmail/services/gmail-message-outbound.service.ts@@ -13,6 +13,7 @@ import { type SendMessageInput } from 'src/modules/messaging/message-outbound-maimport { type SendMessageResult } from 'src/modules/messaging/message-outbound-manager/types/send-message-result.type';import { extractMessageIdFromBuffer } from 'src/modules/messaging/message-outbound-manager/utils/extract-message-id-from-buffer.util';import { formatMessageFromHeader } from 'src/modules/messaging/message-outbound-manager/utils/format-message-from-header.util';+import { getConnectedAccountSendableHandleOrThrow } from 'src/modules/messaging/message-outbound-manager/utils/get-connected-account-sendable-handle-or-throw.util';import { toMailComposerOptions } from 'src/modules/messaging/message-outbound-manager/utils/to-mail-composer-options.util';@Injectable()@@ -163,15 +164,12 @@ export class GmailMessageOutboundService implements MessageOutboundDriver {auth: oAuth2Client,});- const { data: gmailData } = await gmailClient.users.getProfile({- userId: 'me',- });-- const fromEmail = gmailData.emailAddress;-- if (!isNonEmptyString(fromEmail)) {- throw new Error('Gmail profile did not return an email address');- }+ const fromEmail = isNonEmptyString(sendMessageInput.fromHandle)+ ? getConnectedAccountSendableHandleOrThrow({+ connectedAccount,+ requestedFromHandle: sendMessageInput.fromHandle,+ })+ : connectedAccount.handle;const { data: peopleData } = await peopleClient.people.get({resourceName: 'people/me',diff --git a/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/imap/services/imap-smtp-message-outbound.service.ts b/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/imap/services/imap-smtp-message-outbound.service.tsindex 1532e7d60fb..7c168aa8c70 100644--- a/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/imap/services/imap-smtp-message-outbound.service.ts+++ b/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/imap/services/imap-smtp-message-outbound.service.ts@@ -2,6 +2,7 @@ import { Injectable, Logger } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';import MailComposer from 'nodemailer/lib/mail-composer';+import { isNonEmptyString } from '@sniptt/guards';import { isDefined } from 'twenty-shared/utils';import { Repository } from 'typeorm';@@ -19,6 +20,7 @@ import { type SendMessageInput } from 'src/modules/messaging/message-outbound-maimport { type SendMessageResult } from 'src/modules/messaging/message-outbound-manager/types/send-message-result.type';import { extractMessageIdFromBuffer } from 'src/modules/messaging/message-outbound-manager/utils/extract-message-id-from-buffer.util';import { formatMessageFromHeader } from 'src/modules/messaging/message-outbound-manager/utils/format-message-from-header.util';+import { getConnectedAccountSendableHandleOrThrow } from 'src/modules/messaging/message-outbound-manager/utils/get-connected-account-sendable-handle-or-throw.util';import { toMailComposerOptions } from 'src/modules/messaging/message-outbound-manager/utils/to-mail-composer-options.util';@Injectable()@@ -48,7 +50,12 @@ export class ImapSmtpMessageOutboundService implements MessageOutboundDriver {this.assertHandleIsDefined(handle);const from = formatMessageFromHeader({- fromEmail: handle,+ fromEmail: isNonEmptyString(sendMessageInput.fromHandle)+ ? getConnectedAccountSendableHandleOrThrow({+ connectedAccount,+ requestedFromHandle: sendMessageInput.fromHandle,+ })+ : handle,fromName: connectionParameters?.name,});@@ -115,7 +122,12 @@ export class ImapSmtpMessageOutboundService implements MessageOutboundDriver {}const from = formatMessageFromHeader({- fromEmail: handle,+ fromEmail: isNonEmptyString(sendMessageInput.fromHandle)+ ? getConnectedAccountSendableHandleOrThrow({+ connectedAccount,+ requestedFromHandle: sendMessageInput.fromHandle,+ })+ : handle,fromName: connectionParameters?.name,});diff --git a/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/microsoft/services/microsoft-message-outbound.service.ts b/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/microsoft/services/microsoft-message-outbound.service.tsindex 05cade5416c..934db53adcd 100644--- a/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/microsoft/services/microsoft-message-outbound.service.ts+++ b/packages/twenty-server/src/modules/messaging/message-outbound-manager/drivers/microsoft/services/microsoft-message-outbound.service.ts@@ -7,7 +7,9 @@ import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connectimport { toMicrosoftRecipients } from 'src/modules/messaging/message-import-manager/utils/to-microsoft-recipients.util';import { type SendMessageInput } from 'src/modules/messaging/message-outbound-manager/types/send-message-input.type';import { type SendMessageResult } from 'src/modules/messaging/message-outbound-manager/types/send-message-result.type';+import { getConnectedAccountSendableHandleOrThrow } from 'src/modules/messaging/message-outbound-manager/utils/get-connected-account-sendable-handle-or-throw.util';import { type Client as MicrosoftGraphClient } from '@microsoft/microsoft-graph-client';+import { isNonEmptyString } from '@sniptt/guards';import { isDefined } from 'twenty-shared/utils';@Injectable()@@ -30,7 +32,11 @@ export class MicrosoftMessageOutboundService implements MessageOutboundDriver {id: messageId,internetMessageId,conversationId,- } = await this.createDraftMessage(microsoftClient, sendMessageInput);+ } = await this.createDraftMessage({+ microsoftClient,+ sendMessageInput,+ connectedAccount,+ });await microsoftClient.api(`/me/messages/${messageId}/send`).post({});@@ -49,7 +55,11 @@ export class MicrosoftMessageOutboundService implements MessageOutboundDriver {connectedAccount.id,);- await this.createDraftMessage(microsoftClient, sendMessageInput);+ await this.createDraftMessage({+ microsoftClient,+ sendMessageInput,+ connectedAccount,+ });}async sendDraft(@@ -78,22 +88,30 @@ export class MicrosoftMessageOutboundService implements MessageOutboundDriver {return sendResult;}- private async createDraftMessage(- microsoftClient: MicrosoftGraphClient,- sendMessageInput: SendMessageInput,- ): Promise<{+ private async createDraftMessage({+ microsoftClient,+ sendMessageInput,+ connectedAccount,+ }: {+ microsoftClient: MicrosoftGraphClient;+ sendMessageInput: SendMessageInput;+ connectedAccount: ConnectedAccountEntity;+ }): Promise<{id: string;internetMessageId?: string;conversationId?: string;}> {const parentMessageGraphId = sendMessageInput.inReplyTo- ? await this.findMessageByInternetMessageId(+ ? await this.findMessageByInternetMessageId({microsoftClient,- sendMessageInput.inReplyTo,- )+ internetMessageId: sendMessageInput.inReplyTo,+ }): undefined;- const message = this.composeMicrosoftMessage(sendMessageInput);+ const message = this.composeMicrosoftMessage({+ sendMessageInput,+ connectedAccount,+ });if (isDefined(parentMessageGraphId)) {const reply = await microsoftClient@@ -121,10 +139,13 @@ export class MicrosoftMessageOutboundService implements MessageOutboundDriver {};}- private async findMessageByInternetMessageId(- microsoftClient: MicrosoftGraphClient,- internetMessageId: string,- ): Promise<string | undefined> {+ private async findMessageByInternetMessageId({+ microsoftClient,+ internetMessageId,+ }: {+ microsoftClient: MicrosoftGraphClient;+ internetMessageId: string;+ }): Promise<string | undefined> {const escapedInternetMessageId = internetMessageId.split("'").join("''");const response = await microsoftClient@@ -137,11 +158,29 @@ export class MicrosoftMessageOutboundService implements MessageOutboundDriver {return response?.value?.[0]?.id;}- private composeMicrosoftMessage(- sendMessageInput: SendMessageInput,- ): Record<string, unknown> {+ private composeMicrosoftMessage({+ sendMessageInput,+ connectedAccount,+ }: {+ sendMessageInput: SendMessageInput;+ connectedAccount: ConnectedAccountEntity;+ }): Record<string, unknown> {+ const from = isNonEmptyString(sendMessageInput.fromHandle)+ ? {+ from: {+ emailAddress: {+ address: getConnectedAccountSendableHandleOrThrow({+ connectedAccount,+ requestedFromHandle: sendMessageInput.fromHandle,+ }),+ },+ },+ }+ : {};+return {subject: sendMessageInput.subject,+ ...from,body: {contentType: 'HTML',content: sendMessageInput.html,diff --git a/packages/twenty-server/src/modules/messaging/message-outbound-manager/dtos/send-email.input.ts b/packages/twenty-server/src/modules/messaging/message-outbound-manager/dtos/send-email.input.tsindex 5f24549c460..d0cda3ac99f 100644--- a/packages/twenty-server/src/modules/messaging/message-outbound-manager/dtos/send-email.input.ts+++ b/packages/twenty-server/src/modules/messaging/message-outbound-manager/dtos/send-email.input.ts@@ -14,6 +14,9 @@ export class SendEmailInput {@Field(() => String)connectedAccountId: string;+ @Field(() => String, { nullable: true })+ fromHandle?: string;+@Field(() => String)to: string;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 91ba3de5fc1..c06f36e8a30 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@@ -66,6 +66,7 @@ export class SendEmailResolver {subject: input.subject,body: input.body,connectedAccountId: input.connectedAccountId,+ fromHandle: input.fromHandle,files: input.files ?? [],inReplyTo: input.inReplyTo,},diff --git a/packages/twenty-server/src/modules/messaging/message-outbound-manager/services/send-email.service.ts b/packages/twenty-server/src/modules/messaging/message-outbound-manager/services/send-email.service.tsindex e31a2be1a40..b07e1fdba3b 100644--- a/packages/twenty-server/src/modules/messaging/message-outbound-manager/services/send-email.service.ts+++ b/packages/twenty-server/src/modules/messaging/message-outbound-manager/services/send-email.service.ts@@ -62,6 +62,7 @@ export class SendEmailService {private toSendMessageInput(data: ComposedEmail): SendMessageInput {return {+ fromHandle: data.fromHandle,to: data.recipients.to,cc: data.recipients.cc.length > 0 ? data.recipients.cc : undefined,bcc: data.recipients.bcc.length > 0 ? data.recipients.bcc : undefined,diff --git a/packages/twenty-server/src/modules/messaging/message-outbound-manager/types/send-message-input.type.ts b/packages/twenty-server/src/modules/messaging/message-outbound-manager/types/send-message-input.type.tsindex 3c333399ed4..52cc0a2e339 100644--- a/packages/twenty-server/src/modules/messaging/message-outbound-manager/types/send-message-input.type.ts+++ b/packages/twenty-server/src/modules/messaging/message-outbound-manager/types/send-message-input.type.ts@@ -3,6 +3,7 @@ type EmailAddress = string | string[];export type SendMessageInput = {body: string;subject: string;+ fromHandle?: string;to: EmailAddress;cc?: EmailAddress;bcc?: EmailAddress;diff --git a/packages/twenty-server/src/modules/messaging/message-outbound-manager/utils/__tests__/get-connected-account-sendable-handle-or-throw.util.spec.ts b/packages/twenty-server/src/modules/messaging/message-outbound-manager/utils/__tests__/get-connected-account-sendable-handle-or-throw.util.spec.tsnew file mode 100644index 00000000000..343ca5f2188--- /dev/null+++ b/packages/twenty-server/src/modules/messaging/message-outbound-manager/utils/__tests__/get-connected-account-sendable-handle-or-throw.util.spec.ts@@ -0,0 +1,44 @@+import { getConnectedAccountSendableHandleOrThrow } from 'src/modules/messaging/message-outbound-manager/utils/get-connected-account-sendable-handle-or-throw.util';++const connectedAccount = {+ handle: '[email protected]',+ handleAliases: ['[email protected]', '[email protected]'],+};++describe('getConnectedAccountSendableHandleOrThrow', () => {+ it('should accept the connected account handle itself', () => {+ expect(+ getConnectedAccountSendableHandleOrThrow({+ connectedAccount,+ requestedFromHandle: '[email protected]',+ }),+ ).toBe('[email protected]');+ });++ it('should accept a verified alias and return it as the provider spells it', () => {+ expect(+ getConnectedAccountSendableHandleOrThrow({+ connectedAccount,+ requestedFromHandle: ' [email protected] ',+ }),+ ).toBe('[email protected]');+ });++ it('should reject an address the account has not verified', () => {+ expect(() =>+ getConnectedAccountSendableHandleOrThrow({+ connectedAccount,+ requestedFromHandle: '[email protected]',+ }),+ ).toThrow('is not the connected account handle nor one of its verified');+ });++ it('should reject any alias when the account has none', () => {+ expect(() =>+ getConnectedAccountSendableHandleOrThrow({+ connectedAccount: { handle: '[email protected]', handleAliases: null },+ requestedFromHandle: '[email protected]',+ }),+ ).toThrow();+ });+});diff --git a/packages/twenty-server/src/modules/messaging/message-outbound-manager/utils/get-connected-account-sendable-handle-or-throw.util.ts b/packages/twenty-server/src/modules/messaging/message-outbound-manager/utils/get-connected-account-sendable-handle-or-throw.util.tsnew file mode 100644index 00000000000..4ecb8882aa7--- /dev/null+++ b/packages/twenty-server/src/modules/messaging/message-outbound-manager/utils/get-connected-account-sendable-handle-or-throw.util.ts@@ -0,0 +1,37 @@+import { msg } from '@lingui/core/macro';+import { getSendableEmailHandles, isDefined } from 'twenty-shared/utils';++import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';+import {+ MessageChannelException,+ MessageChannelExceptionCode,+} from 'src/engine/metadata-modules/message-channel/message-channel.exception';++export const getConnectedAccountSendableHandleOrThrow = ({+ connectedAccount,+ requestedFromHandle,+}: {+ connectedAccount: Pick<ConnectedAccountEntity, 'handle' | 'handleAliases'>;+ requestedFromHandle: string;+}): string => {+ const normalizedRequestedFromHandle = requestedFromHandle+ .trim()+ .toLowerCase();++ const matchedFromHandle = getSendableEmailHandles(connectedAccount).find(+ (sendableHandle) =>+ sendableHandle.trim().toLowerCase() === normalizedRequestedFromHandle,+ );++ if (!isDefined(matchedFromHandle)) {+ throw new MessageChannelException(+ `Sender ${requestedFromHandle} is not the connected account handle nor one of its verified aliases`,+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,+ {+ userFriendlyMessage: msg`You cannot send from this address.`,+ },+ );+ }++ return matchedFromHandle;+};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 b7f376efd60..51e94231e22 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@@ -363,6 +363,46 @@ describe('SendEmailWorkflowAction', () => {);});+ it('forwards the configured from handle to the email tool', async () => {+ await action.execute({+ currentStepId: 'step-1',+ steps: [+ buildSendEmailStep({+ ...emailInput,+ fromHandle: '[email protected]',+ body: 'hi',+ }),+ ],+ context: {},+ runInfo: { workspaceId: 'workspace-1', workflowRunId: 'run-1' },+ });++ expect(mockSendEmailTool.execute).toHaveBeenCalledWith(+ expect.objectContaining({ fromHandle: '[email protected]' }),+ expect.any(Object),+ );+ });++ it('resolves workflow variables inside the from handle', async () => {+ await action.execute({+ currentStepId: 'step-1',+ steps: [+ buildSendEmailStep({+ ...emailInput,+ fromHandle: '{{trigger.email}}',+ body: 'hi',+ }),+ ],+ context: { trigger: { email: '[email protected]' } },+ runInfo: { workspaceId: 'workspace-1', workflowRunId: 'run-1' },+ });++ expect(mockSendEmailTool.execute).toHaveBeenCalledWith(+ expect.objectContaining({ fromHandle: '[email protected]' }),+ expect.any(Object),+ );+ });+it('throws when the workspace member has no connected account', async () => {workspaceMemberRepository.findOne.mockResolvedValue({ userId: 'user-1' });userWorkspaceRepository.findOne.mockResolvedValue({diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/types/workflow-send-email-action-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/types/workflow-send-email-action-input.type.tsindex 6c0c2924145..3e9dc867c8c 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/types/workflow-send-email-action-input.type.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/types/workflow-send-email-action-input.type.ts@@ -3,6 +3,7 @@ import { type EmailRecipients } from 'twenty-shared/workflow';export type WorkflowSendEmailActionInput = {connectedAccountId: string;+ fromHandle?: string;recipients: EmailRecipients;subject?: string;body?: string;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 b5aa0748371..0e5faf7f955 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@@ -132,6 +132,7 @@ export const buildEmailStepLog = ({bodyBytes: body.bodyBytes,bodyTruncated: body.bodyTruncated,connectedAccountId,+ fromHandle: input.fromHandle,attachmentCount,inReplyTo: input.inReplyTo,error: output.error,diff --git a/packages/twenty-server/test/integration/google/messaging/outbound.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/outbound.integration-spec.tsindex 21964a3eba1..1a4571afded 100644--- a/packages/twenty-server/test/integration/google/messaging/outbound.integration-spec.ts+++ b/packages/twenty-server/test/integration/google/messaging/outbound.integration-spec.ts@@ -2,16 +2,20 @@ import { randomUUID } from 'node:crypto';import { ConnectedAccountProvider } from 'twenty-shared/types';+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';+import { gmailMessage } from 'test/integration/google/mocks/gmail-message.util';import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';import { createCalendarEvent } from 'test/integration/utils/create-calendar-event.util';import { findImportedCalendarEventTitles } from 'test/integration/utils/find-imported-records.util';import { findRecordNodesByFilter } from 'test/integration/utils/find-records-by-filter.util';+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';import { sendEmail } from 'test/integration/utils/send-email.util';const HANDLE = '[email protected]';+const ALIAS = '[email protected]';const RECIPIENTS = {to: '[email protected]',cc: '[email protected]',@@ -50,6 +54,7 @@ const DRAFT_MESSAGE = gmailMessage({describe('Gmail outbound messaging and calendar creation (integration)', () => {const google = setupGoogleMock({handle: HANDLE,+ aliases: [ALIAS],inbox: [PARENT_MESSAGE, DRAFT_MESSAGE],});@@ -219,6 +224,50 @@ describe('Gmail outbound messaging and calendar creation (integration)', () => {expect(result.messageThreadId).toEqual(expect.any(String));}, 60000);+ it('imports the verified aliases during sync and sends from one of them', async () => {+ const connectedAccount = await getCoreRepository<ConnectedAccountEntity>(+ ConnectedAccountEntity,+ ).findOneByOrFail({ id: channel.connectedAccountId });++ expect(connectedAccount.handleAliases).toEqual([ALIAS]);++ const subject = `Gmail alias outbound ${randomUUID()}`;++ const result = await sendEmail({+ connectedAccountId: channel.connectedAccountId,+ fromHandle: ALIAS,+ to: RECIPIENTS.to,+ subject,+ body: '<p>Gmail alias body</p>',+ });++ expect(result).toMatchObject({ success: true });++ const [{ raw }] = google.sentMessages.slice(-1);++ expect(raw).toContain(`<${ALIAS}>`);+ }, 60000);++ it('refuses to send from an address the account has not verified', async () => {+ const sentMessageCount = google.sentMessages.length;++ const result = await sendEmail({+ connectedAccountId: channel.connectedAccountId,+ fromHandle: '[email protected]',+ to: RECIPIENTS.to,+ subject: `Gmail rejected sender ${randomUUID()}`,+ body: '<p>Gmail rejected body</p>',+ });++ expect(result).toMatchObject({+ success: false,+ error: expect.stringContaining(+ 'is not the connected account handle nor one of its verified aliases',+ ),+ });+ expect(google.sentMessages).toHaveLength(sentMessageCount);+ }, 60000);+it('creates and persists a calendar event with invitations and conferencing', async () => {const title = `Google calendar outbound ${randomUUID()}`;diff --git a/packages/twenty-server/test/integration/google/mocks/google-identity-handlers.util.ts b/packages/twenty-server/test/integration/google/mocks/google-identity-handlers.util.tsindex d1ef4f18540..2185973a2cb 100644--- a/packages/twenty-server/test/integration/google/mocks/google-identity-handlers.util.ts+++ b/packages/twenty-server/test/integration/google/mocks/google-identity-handlers.util.ts@@ -3,7 +3,10 @@ import { http, HttpResponse } from 'msw';import { GOOGLE_OAUTH_SCOPES } from 'test/integration/google/mocks/google-oauth-scopes.constant';import { type MswHandler } from 'test/integration/utils/http-mock.util';-export const googleIdentityHandlers = (handle: string): MswHandler[] => [+export const googleIdentityHandlers = (+ handle: string,+ aliases: string[] = [],+): MswHandler[] => [http.get('https://www.googleapis.com/oauth2/v3/userinfo', () =>HttpResponse.json({sub: `google-user-id-${handle}`,@@ -24,6 +27,11 @@ export const googleIdentityHandlers = (handle: string): MswHandler[] => [HttpResponse.json({ names: [{ displayName: 'Jane Austen' }] }),),http.get('*/gmail/v1/users/me/settings/sendAs', () =>- HttpResponse.json({ sendAs: [{ sendAsEmail: handle, isPrimary: true }] }),+ HttpResponse.json({+ sendAs: [+ { sendAsEmail: handle, isPrimary: true },+ ...aliases.map((alias) => ({ sendAsEmail: alias, isPrimary: false })),+ ],+ }),),];diff --git a/packages/twenty-server/test/integration/google/mocks/setup-google-mock.util.ts b/packages/twenty-server/test/integration/google/mocks/setup-google-mock.util.tsindex 01c89d2deae..24e5d9d2940 100644--- a/packages/twenty-server/test/integration/google/mocks/setup-google-mock.util.ts+++ b/packages/twenty-server/test/integration/google/mocks/setup-google-mock.util.ts@@ -65,10 +65,12 @@ const googleApiErrorResponse = ({export const setupGoogleMock = ({handle,+ aliases = [],inbox = [],labels = DEFAULT_LABELS,}: {handle: string;+ aliases?: string[];inbox?: gmail_v1.Schema$Message[];labels?: gmail_v1.Schema$Label[];}): GoogleMock => {@@ -79,7 +81,7 @@ export const setupGoogleMock = ({const httpMock = setupHttpMock(...googleTokenHandlers(),- ...googleIdentityHandlers(handle),+ ...googleIdentityHandlers(handle, aliases),...googleCalendarEventsHandlers([], 'mock-calendar-sync-token'),...gmailMailboxHandlers(inbox, labelStore),http.post('*/gmail/v1/users/me/messages/send', async ({ request }) => {diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util.tsindex 169bb05e23a..930d10bbc4b 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util.ts@@ -24,6 +24,7 @@ export type WorkflowActionStepRun = {status?: WorkflowRunStatusType;stepStatus?: string;stepResult?: Record<string, unknown>;+ stepError?: string;};const createWorkflow = async (name: string): Promise<string> => {@@ -221,6 +222,7 @@ export const runWorkflowActionStep = async ({status: workflowRun?.status,stepStatus: stepInfo?.status,stepResult: stepInfo?.result,+ stepError: stepInfo?.error,};} finally {if (isDefined(workflowRunId)) {diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/workflow-run-test.util.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/workflow-run-test.util.tsindex 385a23a6f49..c5ff5941e69 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/workflow-run-test.util.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/workflow-run-test.util.ts@@ -18,6 +18,7 @@ export type WorkflowRunState = {{status: string;result?: Record<string, unknown>;+ error?: string;}>;flow?: {diff --git a/packages/twenty-server/test/integration/imap/suites/imap-smtp-outbound.integration-spec.ts b/packages/twenty-server/test/integration/imap/suites/imap-smtp-outbound.integration-spec.tsindex 6943c00a00e..19416c25577 100644--- a/packages/twenty-server/test/integration/imap/suites/imap-smtp-outbound.integration-spec.ts+++ b/packages/twenty-server/test/integration/imap/suites/imap-smtp-outbound.integration-spec.ts@@ -134,4 +134,33 @@ describe('IMAP/SMTP outbound messaging (integration)', () => {]),);}, 300000);++ it('refuses to send from an address the account has not verified', async () => {+ const subject = `IMAP/SMTP rejected sender ${randomUUID()}`;++ const result = await sendEmail({+ connectedAccountId,+ fromHandle: '[email protected]',+ to: HANDLE,+ subject,+ body: '<p>SMTP rejected body</p>',+ });++ expect(result).toMatchObject({+ success: false,+ error: expect.stringContaining(+ 'is not the connected account handle nor one of its verified aliases',+ ),+ });+ expect(+ await findRecordNodesByFilter<{ id: string }>(+ 'message',+ 'messages',+ 'id',+ {+ subject: { eq: subject },+ },+ ),+ ).toEqual([]);+ }, 300000);});diff --git a/packages/twenty-server/test/integration/microsoft/messaging/outbound.integration-spec.ts b/packages/twenty-server/test/integration/microsoft/messaging/outbound.integration-spec.tsindex d4e38d82607..82bfe384acf 100644--- a/packages/twenty-server/test/integration/microsoft/messaging/outbound.integration-spec.ts+++ b/packages/twenty-server/test/integration/microsoft/messaging/outbound.integration-spec.ts@@ -2,15 +2,19 @@ import { randomUUID } from 'node:crypto';import { ConnectedAccountProvider } from 'twenty-shared/types';+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';+import { setupMicrosoftMock } from 'test/integration/microsoft/mocks/setup-microsoft-mock.util';import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';import { createCalendarEvent } from 'test/integration/utils/create-calendar-event.util';import { findImportedCalendarEventTitles } from 'test/integration/utils/find-imported-records.util';import { findRecordNodesByFilter } from 'test/integration/utils/find-records-by-filter.util';+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';import { sendEmail } from 'test/integration/utils/send-email.util';const HANDLE = '[email protected]';+const ALIAS = '[email protected]';const RECIPIENTS = {to: '[email protected]',cc: '[email protected]',@@ -35,6 +39,7 @@ const DRAFT_MESSAGE = {describe('Microsoft outbound messaging and calendar creation (integration)', () => {const microsoft = setupMicrosoftMock({handle: HANDLE,+ aliases: [ALIAS],folders: [{ id: 'inbox', displayName: 'Inbox' },{ id: 'sentitems', displayName: 'Sent Items' },@@ -228,6 +233,71 @@ describe('Microsoft outbound messaging and calendar creation (integration)', ()expect(result.messageThreadId).toEqual(expect.any(String));}, 60000);+ it('imports the verified aliases during sync and sends from one of them', async () => {+ const connectedAccount = await getCoreRepository<ConnectedAccountEntity>(+ ConnectedAccountEntity,+ ).findOneByOrFail({ id: channel.connectedAccountId });++ expect(connectedAccount.handleAliases).toEqual([ALIAS]);++ const subject = `Microsoft alias outbound ${randomUUID()}`;++ const result = await sendEmail({+ connectedAccountId: channel.connectedAccountId,+ fromHandle: ALIAS,+ to: RECIPIENTS.to,+ subject,+ body: '<p>Microsoft alias body</p>',+ });++ expect(result).toMatchObject({ success: true });+ expect(microsoft.createdMessages).toEqual([+ expect.objectContaining({+ subject,+ from: { emailAddress: { address: ALIAS } },+ }),+ ]);+ }, 60000);++ it('replies from a verified alias by patching the reply draft', async () => {+ const subject = `Microsoft alias reply ${randomUUID()}`;++ const result = await sendEmail({+ connectedAccountId: channel.connectedAccountId,+ fromHandle: ALIAS,+ to: RECIPIENTS.to,+ subject,+ body: '<p>Microsoft alias reply body</p>',+ inReplyTo: '<[email protected]>',+ });++ expect(result).toMatchObject({ success: true });+ expect(microsoft.patchedMessages).toEqual([+ expect.objectContaining({+ subject,+ from: { emailAddress: { address: ALIAS } },+ }),+ ]);+ }, 60000);++ it('refuses to send from an address the account has not verified', async () => {+ const result = await sendEmail({+ connectedAccountId: channel.connectedAccountId,+ fromHandle: '[email protected]',+ to: RECIPIENTS.to,+ subject: `Microsoft rejected sender ${randomUUID()}`,+ body: '<p>Microsoft rejected body</p>',+ });++ expect(result).toMatchObject({+ success: false,+ error: expect.stringContaining(+ 'is not the connected account handle nor one of its verified aliases',+ ),+ });+ expect(microsoft.createdMessages).toEqual([]);+ }, 60000);+it('creates and persists a calendar event with invitations and conferencing', async () => {const title = `Microsoft calendar outbound ${randomUUID()}`;diff --git a/packages/twenty-server/test/integration/microsoft/mocks/microsoft-auth-handlers.util.ts b/packages/twenty-server/test/integration/microsoft/mocks/microsoft-auth-handlers.util.tsindex f1418fe5725..1c07dbca4a1 100644--- a/packages/twenty-server/test/integration/microsoft/mocks/microsoft-auth-handlers.util.ts+++ b/packages/twenty-server/test/integration/microsoft/mocks/microsoft-auth-handlers.util.ts@@ -5,7 +5,10 @@ import { type MswHandler } from 'test/integration/utils/http-mock.util';export const MICROSOFT_TOKEN_URL ='https://login.microsoftonline.com/common/oauth2/v2.0/token';-export const microsoftAuthHandlers = (handle: string): MswHandler[] => [+export const microsoftAuthHandlers = (+ handle: string,+ aliases: string[] = [],+): MswHandler[] => [http.post(MICROSOFT_TOKEN_URL, () =>HttpResponse.json({token_type: 'Bearer',@@ -24,6 +27,10 @@ export const microsoftAuthHandlers = (handle: string): MswHandler[] => [surname: 'Austen',mail: handle,userPrincipalName: handle,+ proxyAddresses: [+ `SMTP:${handle}`,+ ...aliases.map((alias) => `smtp:${alias}`),+ ],}),),];diff --git a/packages/twenty-server/test/integration/microsoft/mocks/setup-microsoft-mock.util.ts b/packages/twenty-server/test/integration/microsoft/mocks/setup-microsoft-mock.util.tsindex e678b0cb0c1..a14b932044f 100644--- a/packages/twenty-server/test/integration/microsoft/mocks/setup-microsoft-mock.util.ts+++ b/packages/twenty-server/test/integration/microsoft/mocks/setup-microsoft-mock.util.ts@@ -55,10 +55,12 @@ const microsoftGraphErrorResponse = ({export const setupMicrosoftMock = ({handle,+ aliases = [],folders = DEFAULT_FOLDERS,messages = [],}: {handle: string;+ aliases?: string[];folders?: MailFolder[];messages?: Array<Record<string, unknown>>;}): MicrosoftMock => {@@ -74,7 +76,7 @@ export const setupMicrosoftMock = ({const createdCalendarEvents: Event[] = [];const httpMock = setupHttpMock(- ...microsoftAuthHandlers(handle),+ ...microsoftAuthHandlers(handle, aliases),...microsoftMailboxHandlers(folderStore, messages),...microsoftWebhookSubscriptionHandlers(subscriptionStore),http.post('*/me/messages', async ({ request }) => {diff --git a/packages/twenty-server/test/integration/utils/send-email.util.ts b/packages/twenty-server/test/integration/utils/send-email.util.tsindex b70ba2a96ed..c2a545f820a 100644--- a/packages/twenty-server/test/integration/utils/send-email.util.ts+++ b/packages/twenty-server/test/integration/utils/send-email.util.ts@@ -4,6 +4,7 @@ import { makeMetadataAPIRequest } from 'test/integration/metadata/suites/utils/mtype SendEmailInput = {connectedAccountId: string;+ fromHandle?: string;to: string;cc?: string;bcc?: string;diff --git a/packages/twenty-server/test/integration/utils/set-test-connected-account-handle-aliases.util.ts b/packages/twenty-server/test/integration/utils/set-test-connected-account-handle-aliases.util.tsnew file mode 100644index 00000000000..976935b0b1c--- /dev/null+++ b/packages/twenty-server/test/integration/utils/set-test-connected-account-handle-aliases.util.ts@@ -0,0 +1,15 @@+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';++import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';++export const setTestConnectedAccountHandleAliases = async ({+ connectedAccountId,+ handleAliases,+}: {+ connectedAccountId: string;+ handleAliases: string[];+}): Promise<void> => {+ await getCoreRepository<ConnectedAccountEntity>(+ ConnectedAccountEntity,+ ).update({ id: connectedAccountId }, { handleAliases });+};diff --git a/packages/twenty-server/test/integration/workflow-actions/draft-email/drivers/gmail.integration-spec.ts b/packages/twenty-server/test/integration/workflow-actions/draft-email/drivers/gmail.integration-spec.tsindex 647b03a76e3..18c278951f3 100644--- a/packages/twenty-server/test/integration/workflow-actions/draft-email/drivers/gmail.integration-spec.ts+++ b/packages/twenty-server/test/integration/workflow-actions/draft-email/drivers/gmail.integration-spec.ts@@ -6,8 +6,10 @@ import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mockimport { runWorkflowActionStep } from 'test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util';import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';import { findRecordNodesByFilter } from 'test/integration/utils/find-records-by-filter.util';+import { setTestConnectedAccountHandleAliases } from 'test/integration/utils/set-test-connected-account-handle-aliases.util';const HANDLE = '[email protected]';+const ALIAS = '[email protected]';const RECIPIENTS = {to: '[email protected]',cc: '[email protected]',@@ -24,6 +26,10 @@ describe('DRAFT_EMAIL workflow action on Gmail (integration)', () => {provider: ConnectedAccountProvider.GOOGLE,handle: HANDLE,});+ await setTestConnectedAccountHandleAliases({+ connectedAccountId: channel.connectedAccountId,+ handleAliases: [ALIAS],+ });}, 60000);afterAll(async () => {@@ -80,4 +86,30 @@ describe('DRAFT_EMAIL workflow action on Gmail (integration)', () => {),).toEqual([]);}, 60000);++ it('drafts from a verified alias configured on the step', async () => {+ const subject = `Gmail workflow alias draft ${randomUUID()}`;++ const workflowRun = await runWorkflowActionStep({+ name: 'Gmail alias draft email workflow',+ stepType: 'DRAFT_EMAIL',+ input: {+ connectedAccountId: channel.connectedAccountId,+ fromHandle: ALIAS,+ recipients: { to: RECIPIENTS.to, cc: '', bcc: '' },+ subject,+ body: '<p>Gmail workflow alias draft body</p>',+ },+ });++ expect(workflowRun).toMatchObject({+ status: 'COMPLETED',+ stepStatus: 'SUCCESS',+ });++ const [{ raw }] = google.draftMessages.slice(-1);++ expect(raw).toContain(`<${ALIAS}>`);+ expect(google.sentMessages).toEqual([]);+ }, 60000);});diff --git a/packages/twenty-server/test/integration/workflow-actions/draft-email/drivers/microsoft.integration-spec.ts b/packages/twenty-server/test/integration/workflow-actions/draft-email/drivers/microsoft.integration-spec.tsindex 5bbc06c8a42..6ce2ab85584 100644--- a/packages/twenty-server/test/integration/workflow-actions/draft-email/drivers/microsoft.integration-spec.ts+++ b/packages/twenty-server/test/integration/workflow-actions/draft-email/drivers/microsoft.integration-spec.ts@@ -6,8 +6,10 @@ import { runWorkflowActionStep } from 'test/integration/graphql/suites/workflow/import { setupMicrosoftMock } from 'test/integration/microsoft/mocks/setup-microsoft-mock.util';import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';import { findRecordNodesByFilter } from 'test/integration/utils/find-records-by-filter.util';+import { setTestConnectedAccountHandleAliases } from 'test/integration/utils/set-test-connected-account-handle-aliases.util';const HANDLE = '[email protected]';+const ALIAS = '[email protected]';const RECIPIENTS = {to: '[email protected]',cc: '[email protected]',@@ -24,6 +26,10 @@ describe('DRAFT_EMAIL workflow action on Microsoft (integration)', () => {provider: ConnectedAccountProvider.MICROSOFT,handle: HANDLE,});+ await setTestConnectedAccountHandleAliases({+ connectedAccountId: channel.connectedAccountId,+ handleAliases: [ALIAS],+ });}, 60000);afterAll(async () => {@@ -80,4 +86,32 @@ describe('DRAFT_EMAIL workflow action on Microsoft (integration)', () => {),).toEqual([]);}, 60000);++ it('drafts from a verified alias configured on the step', async () => {+ const subject = `Microsoft workflow alias draft ${randomUUID()}`;++ const workflowRun = await runWorkflowActionStep({+ name: 'Microsoft alias draft email workflow',+ stepType: 'DRAFT_EMAIL',+ input: {+ connectedAccountId: channel.connectedAccountId,+ fromHandle: ALIAS,+ recipients: { to: RECIPIENTS.to, cc: '', bcc: '' },+ subject,+ body: '<p>Microsoft workflow alias draft body</p>',+ },+ });++ expect(workflowRun).toMatchObject({+ status: 'COMPLETED',+ stepStatus: 'SUCCESS',+ });+ const [lastCreatedMessage] = microsoft.createdMessages.slice(-1);++ expect(lastCreatedMessage).toMatchObject({+ subject,+ from: { emailAddress: { address: ALIAS } },+ });+ expect(microsoft.sentMessageIds).toEqual([]);+ }, 60000);});diff --git a/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/gmail.integration-spec.ts b/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/gmail.integration-spec.tsindex af2cb57c67e..e83f258f93f 100644--- a/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/gmail.integration-spec.ts+++ b/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/gmail.integration-spec.ts@@ -6,8 +6,10 @@ import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mockimport { runWorkflowActionStep } from 'test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util';import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';import { findRecordNodesByFilter } from 'test/integration/utils/find-records-by-filter.util';+import { setTestConnectedAccountHandleAliases } from 'test/integration/utils/set-test-connected-account-handle-aliases.util';const HANDLE = '[email protected]';+const ALIAS = '[email protected]';const RECIPIENTS = {to: '[email protected]',cc: '[email protected]',@@ -24,6 +26,10 @@ describe('SEND_EMAIL workflow action on Gmail (integration)', () => {provider: ConnectedAccountProvider.GOOGLE,handle: HANDLE,});+ await setTestConnectedAccountHandleAliases({+ connectedAccountId: channel.connectedAccountId,+ handleAliases: [ALIAS],+ });}, 60000);afterAll(async () => {@@ -108,4 +114,54 @@ describe('SEND_EMAIL workflow action on Gmail (integration)', () => {]),);}, 60000);++ it('sends from a verified alias configured on the step', async () => {+ const subject = `Gmail workflow alias send ${randomUUID()}`;++ const workflowRun = await runWorkflowActionStep({+ name: 'Gmail alias send email workflow',+ stepType: 'SEND_EMAIL',+ input: {+ connectedAccountId: channel.connectedAccountId,+ fromHandle: ALIAS,+ recipients: { to: RECIPIENTS.to, cc: '', bcc: '' },+ subject,+ body: '<p>Gmail workflow alias body</p>',+ },+ });++ expect(workflowRun).toMatchObject({+ status: 'COMPLETED',+ stepStatus: 'SUCCESS',+ });++ const [{ raw }] = google.sentMessages.slice(-1);++ expect(raw).toContain(`<${ALIAS}>`);+ }, 60000);++ it('fails the step when the from handle is not a verified alias', async () => {+ const sentMessageCount = google.sentMessages.length;++ const workflowRun = await runWorkflowActionStep({+ name: 'Gmail rejected sender send email workflow',+ stepType: 'SEND_EMAIL',+ input: {+ connectedAccountId: channel.connectedAccountId,+ fromHandle: '[email protected]',+ recipients: { to: RECIPIENTS.to, cc: '', bcc: '' },+ subject: `Gmail workflow rejected sender ${randomUUID()}`,+ body: '<p>Gmail workflow rejected body</p>',+ },+ });++ expect(workflowRun).toMatchObject({+ status: 'FAILED',+ stepStatus: 'FAILED',+ stepError: expect.stringContaining(+ 'is not the connected account handle nor one of its verified aliases',+ ),+ });+ expect(google.sentMessages).toHaveLength(sentMessageCount);+ }, 60000);});diff --git a/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/imap-smtp.integration-spec.ts b/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/imap-smtp.integration-spec.tsindex 5cf542f7df6..c5533819b0e 100644--- a/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/imap-smtp.integration-spec.ts+++ b/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/imap-smtp.integration-spec.ts@@ -151,4 +151,36 @@ describe('SEND_EMAIL workflow action on SMTP (integration)', () => {]),);}, 300000);++ it('fails the step when the from handle is not a verified alias', async () => {+ const subject = `IMAP/SMTP workflow rejected sender ${randomUUID()}`;++ const workflowRun = await runWorkflowActionStep({+ name: 'IMAP/SMTP rejected sender send email workflow',+ stepType: 'SEND_EMAIL',+ input: {+ connectedAccountId,+ fromHandle: '[email protected]',+ recipients: { to: HANDLE, cc: '', bcc: '' },+ subject,+ body: '<p>SMTP workflow rejected body</p>',+ },+ });++ expect(workflowRun).toMatchObject({+ status: 'FAILED',+ stepStatus: 'FAILED',+ stepError: expect.stringContaining(+ 'is not the connected account handle nor one of its verified aliases',+ ),+ });+ expect(+ await findRecordNodesByFilter<{ id: string }>(+ 'message',+ 'messages',+ 'id',+ { subject: { eq: subject } },+ ),+ ).toEqual([]);+ }, 300000);});diff --git a/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/microsoft.integration-spec.ts b/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/microsoft.integration-spec.tsindex 809e74b7bd1..e2c59f48e2f 100644--- a/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/microsoft.integration-spec.ts+++ b/packages/twenty-server/test/integration/workflow-actions/send-email/drivers/microsoft.integration-spec.ts@@ -6,8 +6,10 @@ import { runWorkflowActionStep } from 'test/integration/graphql/suites/workflow/import { setupMicrosoftMock } from 'test/integration/microsoft/mocks/setup-microsoft-mock.util';import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';import { findRecordNodesByFilter } from 'test/integration/utils/find-records-by-filter.util';+import { setTestConnectedAccountHandleAliases } from 'test/integration/utils/set-test-connected-account-handle-aliases.util';const HANDLE = '[email protected]';+const ALIAS = '[email protected]';const RECIPIENTS = {to: '[email protected]',cc: '[email protected]',@@ -24,6 +26,10 @@ describe('SEND_EMAIL workflow action on Microsoft (integration)', () => {provider: ConnectedAccountProvider.MICROSOFT,handle: HANDLE,});+ await setTestConnectedAccountHandleAliases({+ connectedAccountId: channel.connectedAccountId,+ handleAliases: [ALIAS],+ });}, 60000);afterAll(async () => {@@ -115,4 +121,56 @@ describe('SEND_EMAIL workflow action on Microsoft (integration)', () => {]),);}, 60000);++ it('sends from a verified alias configured on the step', async () => {+ const subject = `Microsoft workflow alias send ${randomUUID()}`;++ const workflowRun = await runWorkflowActionStep({+ name: 'Microsoft alias send email workflow',+ stepType: 'SEND_EMAIL',+ input: {+ connectedAccountId: channel.connectedAccountId,+ fromHandle: ALIAS,+ recipients: { to: RECIPIENTS.to, cc: '', bcc: '' },+ subject,+ body: '<p>Microsoft workflow alias body</p>',+ },+ });++ expect(workflowRun).toMatchObject({+ status: 'COMPLETED',+ stepStatus: 'SUCCESS',+ });+ const [lastCreatedMessage] = microsoft.createdMessages.slice(-1);++ expect(lastCreatedMessage).toMatchObject({+ subject,+ from: { emailAddress: { address: ALIAS } },+ });+ }, 60000);++ it('fails the step when the from handle is not a verified alias', async () => {+ const createdMessageCount = microsoft.createdMessages.length;++ const workflowRun = await runWorkflowActionStep({+ name: 'Microsoft rejected sender send email workflow',+ stepType: 'SEND_EMAIL',+ input: {+ connectedAccountId: channel.connectedAccountId,+ fromHandle: '[email protected]',+ recipients: { to: RECIPIENTS.to, cc: '', bcc: '' },+ subject: `Microsoft workflow rejected sender ${randomUUID()}`,+ body: '<p>Microsoft workflow rejected body</p>',+ },+ });++ expect(workflowRun).toMatchObject({+ status: 'FAILED',+ stepStatus: 'FAILED',+ stepError: expect.stringContaining(+ 'is not the connected account handle nor one of its verified aliases',+ ),+ });+ expect(microsoft.createdMessages).toHaveLength(createdMessageCount);+ }, 60000);});diff --git a/packages/twenty-shared/src/utils/email/getSendableEmailHandles.ts b/packages/twenty-shared/src/utils/email/getSendableEmailHandles.tsnew file mode 100644index 00000000000..fd10f446120--- /dev/null+++ b/packages/twenty-shared/src/utils/email/getSendableEmailHandles.ts@@ -0,0 +1,9 @@+import { isNonEmptyString } from '@sniptt/guards';++export const getSendableEmailHandles = (connectedAccount: {+ handle: string;+ handleAliases?: string[] | null;+}): string[] =>+ [connectedAccount.handle, ...(connectedAccount.handleAliases ?? [])].filter(+ isNonEmptyString,+ );diff --git a/packages/twenty-shared/src/utils/index.ts b/packages/twenty-shared/src/utils/index.tsindex 6ddf1f27bdb..8684bae118e 100644--- a/packages/twenty-shared/src/utils/index.ts+++ b/packages/twenty-shared/src/utils/index.ts@@ -51,6 +51,7 @@ export { turnPlainDateIntoUserTimeZoneInstantString } from './date/turnPlainDateexport { turnPlainDateToShiftedDateInSystemTimeZone } from './date/turnPlainDateToShiftedDateInSystemTimeZone';export { deepMerge } from './deepMerge';export { formatEmailAddress } from './email/formatEmailAddress';+export { getSendableEmailHandles } from './email/getSendableEmailHandles';export type { ParsedEmailAddress } from './email/parseEmailAddressList';export { parseEmailAddressList } from './email/parseEmailAddressList';export { CustomError } from './errors/CustomError';diff --git a/packages/twenty-shared/src/workflow/schemas/send-email-action-settings-schema.ts b/packages/twenty-shared/src/workflow/schemas/send-email-action-settings-schema.tsindex 9a75a8d9ce4..b800910135f 100644--- a/packages/twenty-shared/src/workflow/schemas/send-email-action-settings-schema.ts+++ b/packages/twenty-shared/src/workflow/schemas/send-email-action-settings-schema.ts@@ -21,6 +21,7 @@ export const workflowSendEmailActionSettingsSchema =baseWorkflowActionSettingsSchema.extend({input: z.object({connectedAccountId: z.string(),+ fromHandle: z.string().trim().optional(),recipients: z.object({to: z.string().optional().default(''),cc: z.string().optional().default(''),diff --git a/packages/twenty-shared/src/workflow/schemas/workflow-run-step-log-schema.ts b/packages/twenty-shared/src/workflow/schemas/workflow-run-step-log-schema.tsindex 1d6dffd39be..0144945c9fb 100644--- a/packages/twenty-shared/src/workflow/schemas/workflow-run-step-log-schema.ts+++ b/packages/twenty-shared/src/workflow/schemas/workflow-run-step-log-schema.ts@@ -88,6 +88,7 @@ const emailStepLogDetailsSchema = z.object({bodyBytes: z.number().optional(),bodyTruncated: z.boolean().optional(),connectedAccountId: z.string().optional(),+ fromHandle: z.string().optional(),attachmentCount: z.number().optional(),inReplyTo: z.string().optional(),error: z.string().optional(),