feat: add email forwarding message channel (#19535)

## Summary

- Add email forwarding as a new message channel type, allowing users to
forward emails from addresses like `support@mycompany.com` into Twenty
- Inbound emails arrive via S3 (SES → S3 bucket), are polled by a cron
job, parsed, routed to the correct workspace/channel, and persisted as
messages
- Dedicated settings page at `/settings/accounts/new-email-forwarding`
where users provide their source email handle and receive a unique
forwarding address
- Forwarding channels bypass the IMAP/mailbox sync state machine — they
skip cron-driven sync, relaunch, and message-list-fetch lifecycle stages
- Forwarding address section shown at the top of the Emails settings
page so users can find/copy their addresses after initial setup
- Tab names for forwarding channels display the user-provided handle
(e.g. `support@mycompany.com`) instead of the internal routing address
- Shared utilities extracted from IMAP driver: `extractThreadId`,
`extractParticipants`, `extractAddresses` to avoid code duplication
- Uses the existing S3 bucket (STORAGE_S3_*) with `inbound-email/`
prefix — no separate bucket needed
- Feature gated behind `isEmailForwardingEnabled` client config
(requires `INBOUND_EMAIL_DOMAIN` + S3 storage)

## New backend modules

- `InboundEmailS3ClientProvider` — lazy-initialized S3 client using
existing storage config
- `InboundEmailStorageService` — S3 operations (get, move to
processed/unmatched/failed)
- `InboundEmailParserService` — RFC 822 parsing via `postal-mime`,
builds `MessageWithParticipants`
- `InboundEmailImportService` — orchestrates download → parse → route →
persist → archive
- `MessagingInboundEmailPollCronJob` — polls S3 `incoming/` prefix,
enqueues import jobs
- `CreateEmailForwardingChannelInput` DTO — accepts user-provided
`handle`

## New frontend components

- `SettingsAccountsNewEmailForwardingChannel` — dedicated page with
handle input form + forwarding address result
- `SettingsAccountsEmailForwardingSection` — forwarding address list on
the Emails settings page
- `useConnectedAccountHandleMap` — shared hook for account ID → handle
lookup
- `useCreateEmailForwardingChannel` — mutation hook accepting handle
parameter

## Test plan

- [x] 17 unit tests for inbound email import service (all outcomes:
imported, unmatched, loop_dropped, unconfigured, parse_failed,
persist_failed)
- [x] 16 tests for `computeSyncStatus` including EMAIL_FORWARDING cases
- [x] 11 tests for `extractEnvelopeRecipient` utility
- [x] TypeScript typechecks pass for both twenty-server and twenty-front
- [x] Lint passes for both packages
- [ ] Manual: create forwarding channel, verify forwarding address
generated
- [ ] Manual: send email to forwarding address, verify it appears in
Twenty

https://claude.ai/code/session_01KpyF6p4cUEnuaT4h8DP5Pm

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: neo773 <62795688+neo773@users.noreply.github.com>
Co-authored-by: neo773 <neo773@protonmail.com>
This commit is contained in:
Félix Malfait
2026-05-09 11:00:57 +02:00
committed by GitHub
parent 23aa859502
commit 4da8878697
81 changed files with 1967 additions and 309 deletions
@@ -1,4 +1,4 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`ALL_UNIVERSAL_FLAT_ENTITY_PROPERTIES_TO_COMPARE_AND_STRINGIFY should match snapshot 1`] = `
{
@@ -0,0 +1,12 @@
import { Field, InputType } from '@nestjs/graphql';
import { IsEmail, IsNotEmpty, IsString, MaxLength } from 'class-validator';
@InputType('CreateEmailGroupChannelInput')
export class CreateEmailGroupChannelInput {
@Field()
@IsString()
@IsNotEmpty()
@IsEmail()
@MaxLength(254)
handle: string;
}
@@ -0,0 +1,12 @@
import { Field, ObjectType } from '@nestjs/graphql';
import { MessageChannelDTO } from 'src/engine/metadata-modules/message-channel/dtos/message-channel.dto';
@ObjectType('CreateEmailGroupChannelOutput')
export class CreateEmailGroupChannelOutput {
@Field(() => MessageChannelDTO)
messageChannel: MessageChannelDTO;
@Field()
forwardingAddress: string;
}
@@ -1,21 +1,33 @@
import { randomBytes } from 'crypto';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { isNonEmptyString } from '@sniptt/guards';
import { In, Repository } from 'typeorm';
import {
ConnectedAccountProvider,
MessageChannelContactAutoCreationPolicy,
MessageChannelPendingGroupEmailsAction,
MessageChannelSyncStage,
MessageChannelSyncStatus,
MessageChannelType,
MessageChannelVisibility,
} from 'twenty-shared/types';
import { StorageDriverType } from 'src/engine/core-modules/file-storage/interfaces/file-storage.interface';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { ConnectedAccountMetadataService } from 'src/engine/metadata-modules/connected-account/connected-account-metadata.service';
import { CreateEmailGroupChannelOutput } from 'src/engine/metadata-modules/message-channel/dtos/create-email-group-channel.output';
import { MessageChannelDTO } from 'src/engine/metadata-modules/message-channel/dtos/message-channel.dto';
import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import {
MessageChannelException,
MessageChannelExceptionCode,
} from 'src/engine/metadata-modules/message-channel/message-channel.exception';
import { INBOUND_EMAIL_LOCAL_PART_PREFIX } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/constants/inbound-email-local-part-prefix.constant';
import { INBOUND_EMAIL_LOCAL_PART_RANDOM_BYTES } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/constants/inbound-email-local-part-random-bytes.constant';
@Injectable()
export class MessageChannelMetadataService {
@@ -23,6 +35,7 @@ export class MessageChannelMetadataService {
@InjectRepository(MessageChannelEntity)
private readonly repository: Repository<MessageChannelEntity>,
private readonly connectedAccountMetadataService: ConnectedAccountMetadataService,
private readonly twentyConfigService: TwentyConfigService,
) {}
async findAll(workspaceId: string): Promise<MessageChannelDTO[]> {
@@ -172,6 +185,65 @@ export class MessageChannelMetadataService {
return this.repository.findOneOrFail({ where: { id, workspaceId } });
}
async createEmailGroupChannel({
handle,
userWorkspaceId,
workspaceId,
}: {
handle: string;
userWorkspaceId: string;
workspaceId: string;
}): Promise<CreateEmailGroupChannelOutput> {
const inboundEmailDomain = this.twentyConfigService.get(
'INBOUND_EMAIL_DOMAIN',
);
const storageType = this.twentyConfigService.get('STORAGE_TYPE');
if (
!isNonEmptyString(inboundEmailDomain) ||
storageType !== StorageDriverType.S_3
) {
throw new MessageChannelException(
'Email group is not configured: INBOUND_EMAIL_DOMAIN must be set and STORAGE_TYPE must be S3',
MessageChannelExceptionCode.EMAIL_GROUP_NOT_CONFIGURED,
);
}
const localPart =
INBOUND_EMAIL_LOCAL_PART_PREFIX +
randomBytes(INBOUND_EMAIL_LOCAL_PART_RANDOM_BYTES).toString('hex');
const forwardingAddress = `${localPart}@${inboundEmailDomain}`;
const connectedAccount = await this.connectedAccountMetadataService.create({
workspaceId,
handle,
provider: ConnectedAccountProvider.EMAIL_GROUP,
userWorkspaceId,
accessToken: null,
refreshToken: null,
});
const messageChannel = await this.create({
workspaceId,
handle: forwardingAddress,
connectedAccountId: connectedAccount.id,
type: MessageChannelType.EMAIL_GROUP,
visibility: MessageChannelVisibility.SHARE_EVERYTHING,
syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
syncStatus: MessageChannelSyncStatus.ACTIVE,
isSyncEnabled: true,
isContactAutoCreationEnabled: true,
contactAutoCreationPolicy:
MessageChannelContactAutoCreationPolicy.SENT_AND_RECEIVED,
excludeGroupEmails: false,
excludeNonProfessionalEmails: false,
pendingGroupEmailsAction: MessageChannelPendingGroupEmailsAction.NONE,
});
return { messageChannel, forwardingAddress };
}
async delete({
id,
workspaceId,
@@ -8,6 +8,7 @@ export enum MessageChannelExceptionCode {
MESSAGE_CHANNEL_NOT_FOUND = 'MESSAGE_CHANNEL_NOT_FOUND',
INVALID_MESSAGE_CHANNEL_INPUT = 'INVALID_MESSAGE_CHANNEL_INPUT',
MESSAGE_CHANNEL_OWNERSHIP_VIOLATION = 'MESSAGE_CHANNEL_OWNERSHIP_VIOLATION',
EMAIL_GROUP_NOT_CONFIGURED = 'EMAIL_GROUP_NOT_CONFIGURED',
}
const getMessageChannelExceptionUserFriendlyMessage = (
@@ -20,6 +21,8 @@ const getMessageChannelExceptionUserFriendlyMessage = (
return msg`Invalid message channel input.`;
case MessageChannelExceptionCode.MESSAGE_CHANNEL_OWNERSHIP_VIOLATION:
return msg`You do not have access to this message channel.`;
case MessageChannelExceptionCode.EMAIL_GROUP_NOT_CONFIGURED:
return msg`Email group is not configured on this server.`;
default:
assertUnreachable(code);
}
@@ -1,5 +1,5 @@
import { UseGuards, UseInterceptors } from '@nestjs/common';
import { Args, Mutation, Query } from '@nestjs/graphql';
import { Args, Mutation, Parent, Query, ResolveField } from '@nestjs/graphql';
import { InjectRepository } from '@nestjs/typeorm';
import { isDefined } from 'twenty-shared/utils';
@@ -9,6 +9,7 @@ import { Not, Repository } from 'typeorm';
import {
MessageChannelPendingGroupEmailsAction,
MessageChannelSyncStage,
MessageChannelType,
MessageFolderPendingSyncAction,
} from 'twenty-shared/types';
import { type MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
@@ -19,6 +20,10 @@ import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-worksp
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
import { CreateEmailGroupChannelInput } from 'src/engine/metadata-modules/message-channel/dtos/create-email-group-channel.input';
import { CreateEmailGroupChannelOutput } from 'src/engine/metadata-modules/message-channel/dtos/create-email-group-channel.output';
import { ConnectedAccountMetadataService } from 'src/engine/metadata-modules/connected-account/connected-account-metadata.service';
import { ConnectedAccountPublicDTO } from 'src/engine/metadata-modules/connected-account/dtos/connected-account-public.dto';
import { MessageChannelDTO } from 'src/engine/metadata-modules/message-channel/dtos/message-channel.dto';
import { UpdateMessageChannelInput } from 'src/engine/metadata-modules/message-channel/dtos/update-message-channel.input';
import {
@@ -36,11 +41,40 @@ import { MessagingProcessGroupEmailActionsService } from 'src/modules/messaging/
export class MessageChannelResolver {
constructor(
private readonly messageChannelMetadataService: MessageChannelMetadataService,
private readonly connectedAccountMetadataService: ConnectedAccountMetadataService,
@InjectRepository(MessageFolderEntity)
private readonly messageFolderRepository: Repository<MessageFolderEntity>,
private readonly messagingProcessGroupEmailActionsService: MessagingProcessGroupEmailActionsService,
) {}
@ResolveField('connectedAccount', () => ConnectedAccountPublicDTO, {
nullable: true,
})
async connectedAccount(
@Parent() messageChannel: MessageChannelDTO,
@AuthWorkspace() workspace: WorkspaceEntity,
@AuthUserWorkspaceId() userWorkspaceId: string,
): Promise<ConnectedAccountPublicDTO | null> {
const connectedAccount =
await this.connectedAccountMetadataService.findById({
id: messageChannel.connectedAccountId,
workspaceId: workspace.id,
});
if (!isDefined(connectedAccount)) {
return null;
}
if (
messageChannel.type !== MessageChannelType.EMAIL_GROUP &&
connectedAccount.userWorkspaceId !== userWorkspaceId
) {
return null;
}
return connectedAccount;
}
@Query(() => [MessageChannelDTO])
@UseGuards(NoPermissionGuard)
async myMessageChannels(
@@ -130,4 +164,47 @@ export class MessageChannelResolver {
data: input.update,
});
}
@Mutation(() => CreateEmailGroupChannelOutput)
@UseGuards(NoPermissionGuard)
async createEmailGroupChannel(
@Args('input') input: CreateEmailGroupChannelInput,
@AuthWorkspace() workspace: WorkspaceEntity,
@AuthUserWorkspaceId() userWorkspaceId: string,
): Promise<CreateEmailGroupChannelOutput> {
return this.messageChannelMetadataService.createEmailGroupChannel({
handle: input.handle,
userWorkspaceId,
workspaceId: workspace.id,
});
}
@Mutation(() => MessageChannelDTO)
@UseGuards(NoPermissionGuard)
async deleteEmailGroupChannel(
@Args('id', { type: () => UUIDScalarType }) id: string,
@AuthWorkspace() workspace: WorkspaceEntity,
@AuthUserWorkspaceId() userWorkspaceId: string,
): Promise<MessageChannelDTO> {
const messageChannel =
await this.messageChannelMetadataService.verifyOwnership({
id,
userWorkspaceId,
workspaceId: workspace.id,
});
if (messageChannel.type !== MessageChannelType.EMAIL_GROUP) {
throw new MessageChannelException(
`Message channel ${id} is not an email group`,
MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
);
}
await this.connectedAccountMetadataService.delete({
id: messageChannel.connectedAccountId,
workspaceId: workspace.id,
});
return messageChannel;
}
}
@@ -2,6 +2,7 @@ import { assertUnreachable } from 'twenty-shared/utils';
import {
ForbiddenError,
InternalServerError,
NotFoundError,
UserInputError,
} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
@@ -23,6 +24,8 @@ export const messageChannelGraphqlApiExceptionHandler = (error: Error) => {
throw new UserInputError(error);
case MessageChannelExceptionCode.MESSAGE_CHANNEL_OWNERSHIP_VIOLATION:
throw new ForbiddenError(error);
case MessageChannelExceptionCode.EMAIL_GROUP_NOT_CONFIGURED:
throw new InternalServerError(error);
default: {
return assertUnreachable(error.code);
}