Skip to content

The open alternative to Salesforce, designed for AI.

Fix attachments missing from Outlook drafts created by the Draft Email action (#25529)

neo77352542a000817
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.ts
index 934db53adcd..649b3e74b2e 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
@@ -12,6 +12,12 @@ import { type Client as MicrosoftGraphClient } from '@microsoft/microsoft-graph-
import { isNonEmptyString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
+type MicrosoftDraftMessage = {
+ id: string;
+ internetMessageId?: string;
+ conversationId?: string;
+};
+
@Injectable()
export class MicrosoftMessageOutboundService implements MessageOutboundDriver {
private readonly logger = new Logger(MicrosoftMessageOutboundService.name);
@@ -96,11 +102,7 @@ export class MicrosoftMessageOutboundService implements MessageOutboundDriver {
microsoftClient: MicrosoftGraphClient;
sendMessageInput: SendMessageInput;
connectedAccount: ConnectedAccountEntity;
- }): Promise<{
- id: string;
- internetMessageId?: string;
- conversationId?: string;
- }> {
+ }): Promise<MicrosoftDraftMessage> {
const parentMessageGraphId = sendMessageInput.inReplyTo
? await this.findMessageByInternetMessageId({
microsoftClient,
@@ -113,23 +115,41 @@ export class MicrosoftMessageOutboundService implements MessageOutboundDriver {
connectedAccount,
});
- if (isDefined(parentMessageGraphId)) {
- const reply = await microsoftClient
- .api(`/me/messages/${parentMessageGraphId}/createReply`)
- .post({});
-
- const patched = await microsoftClient
- .api(`/me/messages/${reply.id}`)
- .patch(message);
-
- return {
- id: reply.id,
- internetMessageId:
- patched?.internetMessageId ?? reply.internetMessageId,
- conversationId: patched?.conversationId ?? reply.conversationId,
- };
- }
+ const draftMessage = isDefined(parentMessageGraphId)
+ ? await this.createReplyDraftMessage({
+ microsoftClient,
+ parentMessageGraphId,
+ message,
+ })
+ : await this.createNewDraftMessage({ microsoftClient, message });
+
+ await this.postAttachmentsToMessageCollection({
+ microsoftClient,
+ messageId: draftMessage.id,
+ attachments: sendMessageInput.attachments,
+ }).catch(async (error) => {
+ await microsoftClient
+ .api(`/me/messages/${draftMessage.id}`)
+ .delete()
+ .catch((deletionError) =>
+ this.logger.warn(
+ `Failed to delete Microsoft draft ${draftMessage.id} after its attachments failed to upload: ${deletionError}`,
+ ),
+ );
+
+ throw error;
+ });
+ return draftMessage;
+ }
+
+ private async createNewDraftMessage({
+ microsoftClient,
+ message,
+ }: {
+ microsoftClient: MicrosoftGraphClient;
+ message: Record<string, unknown>;
+ }): Promise<MicrosoftDraftMessage> {
const response = await microsoftClient.api('/me/messages').post(message);
return {
@@ -139,6 +159,53 @@ export class MicrosoftMessageOutboundService implements MessageOutboundDriver {
};
}
+ private async createReplyDraftMessage({
+ microsoftClient,
+ parentMessageGraphId,
+ message,
+ }: {
+ microsoftClient: MicrosoftGraphClient;
+ parentMessageGraphId: string;
+ message: Record<string, unknown>;
+ }): Promise<MicrosoftDraftMessage> {
+ const reply = await microsoftClient
+ .api(`/me/messages/${parentMessageGraphId}/createReply`)
+ .post({});
+
+ const patched = await microsoftClient
+ .api(`/me/messages/${reply.id}`)
+ .patch(message);
+
+ return {
+ id: reply.id,
+ internetMessageId: patched?.internetMessageId ?? reply.internetMessageId,
+ conversationId: patched?.conversationId ?? reply.conversationId,
+ };
+ }
+
+ private async postAttachmentsToMessageCollection({
+ microsoftClient,
+ messageId,
+ attachments,
+ }: {
+ microsoftClient: MicrosoftGraphClient;
+ messageId: string;
+ attachments: SendMessageInput['attachments'];
+ }): Promise<void> {
+ if (!isDefined(attachments)) {
+ return;
+ }
+
+ for (const attachment of attachments) {
+ await microsoftClient.api(`/me/messages/${messageId}/attachments`).post({
+ '@odata.type': '#microsoft.graph.fileAttachment',
+ name: attachment.filename,
+ contentType: attachment.contentType,
+ contentBytes: attachment.content.toString('base64'),
+ });
+ }
+ }
+
private async findMessageByInternetMessageId({
microsoftClient,
internetMessageId,
@@ -188,17 +255,6 @@ export class MicrosoftMessageOutboundService implements MessageOutboundDriver {
toRecipients: toMicrosoftRecipients(sendMessageInput.to),
ccRecipients: toMicrosoftRecipients(sendMessageInput.cc),
bccRecipients: toMicrosoftRecipients(sendMessageInput.bcc),
- ...(sendMessageInput.attachments &&
- sendMessageInput.attachments.length > 0
- ? {
- attachments: sendMessageInput.attachments.map((attachment) => ({
- '@odata.type': '#microsoft.graph.fileAttachment',
- name: attachment.filename,
- contentType: attachment.contentType,
- contentBytes: attachment.content.toString('base64'),
- })),
- }
- : {}),
};
}
}
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.ts
index 34b66dde085..f1a77ce80a2 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
@@ -28,6 +28,7 @@ export type MicrosoftMock = {
subscriptions: MicrosoftSubscriptionStore;
createdMessages: Array<Record<string, unknown>>;
patchedMessages: Array<Record<string, unknown>>;
+ createdAttachments: Array<Record<string, unknown>>;
sentMessageIds: string[];
createdCalendarEvents: Event[];
serveCalendarEvents: (
@@ -72,6 +73,7 @@ export const setupMicrosoftMock = ({
const subscriptionStore = createMicrosoftSubscriptionStore();
const createdMessages: Array<Record<string, unknown>> = [];
const patchedMessages: Array<Record<string, unknown>> = [];
+ const createdAttachments: Array<Record<string, unknown>> = [];
const sentMessageIds: string[] = [];
const createdCalendarEvents: Event[] = [];
@@ -91,6 +93,22 @@ export const setupMicrosoftMock = ({
conversationId: `microsoft-conversation-${createdMessages.length}`,
});
}),
+ http.post(
+ '*/me/messages/:messageId/attachments',
+ async ({ request, params }) => {
+ const attachment = (await request.json()) as Record<string, unknown>;
+
+ createdAttachments.push({
+ messageId: params.messageId as string,
+ ...attachment,
+ });
+
+ return HttpResponse.json({
+ id: `microsoft-attachment-${createdAttachments.length}`,
+ ...attachment,
+ });
+ },
+ ),
http.post('*/me/messages/:messageId/send', ({ params }) => {
sentMessageIds.push(params.messageId as string);
@@ -150,6 +168,7 @@ export const setupMicrosoftMock = ({
subscriptions: subscriptionStore,
createdMessages,
patchedMessages,
+ createdAttachments,
sentMessageIds,
createdCalendarEvents,
serveCalendarEvents: (
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.ts
index 6ce2ab85584..28482020b11 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
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto';
import { ConnectedAccountProvider } from 'twenty-shared/types';
import { runWorkflowActionStep } from 'test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util';
+import { uploadFileWithDirectUpload } from 'test/integration/graphql/utils/upload-file-with-direct-upload.util';
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';
@@ -15,6 +16,24 @@ const RECIPIENTS = {
};
+const ATTACHMENT_CONTENT = Buffer.from('draft attachment content');
+const PARENT_INTERNET_MESSAGE_ID = '<[email protected]>';
+
+const uploadAttachmentFile = async (filename: string) => {
+ const uploadedFile = await uploadFileWithDirectUpload({
+ filename,
+ content: ATTACHMENT_CONTENT,
+ fileFolder: 'Workflow',
+ });
+
+ return {
+ id: uploadedFile.id,
+ name: filename,
+ size: uploadedFile.size,
+ type: 'text/plain',
+ createdAt: uploadedFile.createdAt,
+ };
+};
describe('DRAFT_EMAIL workflow action on Microsoft (integration)', () => {
const microsoft = setupMicrosoftMock({ handle: HANDLE });
@@ -114,4 +133,76 @@ describe('DRAFT_EMAIL workflow action on Microsoft (integration)', () => {
});
expect(microsoft.sentMessageIds).toEqual([]);
}, 60000);
+
+ it('attaches files to the drafted message', async () => {
+ const subject = `Microsoft workflow draft with attachment ${randomUUID()}`;
+ const file = await uploadAttachmentFile('draft-attachment.txt');
+ const attachmentsBefore = microsoft.createdAttachments.length;
+ const messagesBefore = microsoft.createdMessages.length;
+
+ const workflowRun = await runWorkflowActionStep({
+ name: 'Microsoft draft email with attachment workflow',
+ stepType: 'DRAFT_EMAIL',
+ input: {
+ connectedAccountId: channel.connectedAccountId,
+ recipients: { to: RECIPIENTS.to, cc: '', bcc: '' },
+ subject,
+ body: '<p>Microsoft workflow draft body</p>',
+ files: [file],
+ },
+ });
+
+ expect(workflowRun).toMatchObject({
+ status: 'COMPLETED',
+ stepStatus: 'SUCCESS',
+ });
+
+ expect(microsoft.createdAttachments.slice(attachmentsBefore)).toMatchObject(
+ [
+ {
+ messageId: `microsoft-message-${messagesBefore + 1}`,
+ '@odata.type': '#microsoft.graph.fileAttachment',
+ name: 'draft-attachment.txt',
+ contentBytes: ATTACHMENT_CONTENT.toString('base64'),
+ },
+ ],
+ );
+ expect(microsoft.sentMessageIds).toEqual([]);
+ }, 60000);
+
+ it('attaches files to a drafted reply', async () => {
+ const subject = `Microsoft workflow reply draft with attachment ${randomUUID()}`;
+ const file = await uploadAttachmentFile('reply-attachment.txt');
+ const attachmentsBefore = microsoft.createdAttachments.length;
+
+ const workflowRun = await runWorkflowActionStep({
+ name: 'Microsoft draft reply with attachment workflow',
+ stepType: 'DRAFT_EMAIL',
+ input: {
+ connectedAccountId: channel.connectedAccountId,
+ recipients: { to: RECIPIENTS.to, cc: '', bcc: '' },
+ subject,
+ body: '<p>Microsoft workflow reply draft body</p>',
+ files: [file],
+ inReplyTo: PARENT_INTERNET_MESSAGE_ID,
+ },
+ });
+
+ expect(workflowRun).toMatchObject({
+ status: 'COMPLETED',
+ stepStatus: 'SUCCESS',
+ });
+
+ expect(microsoft.createdAttachments.slice(attachmentsBefore)).toMatchObject(
+ [
+ {
+ messageId: 'microsoft-reply-message',
+ '@odata.type': '#microsoft.graph.fileAttachment',
+ name: 'reply-attachment.txt',
+ contentBytes: ATTACHMENT_CONTENT.toString('base64'),
+ },
+ ],
+ );
+ expect(microsoft.sentMessageIds).toEqual([]);
+ }, 60000);
});