Skip to content

πŸ”₯ πŸ”₯ πŸ”₯ A Free & Self-hostable Airtable Alternative

feat: send record via email

DarkPhoenix2704134ef53e732e
diff --git a/packages/nc-gui/components/dlg/SendRecordEmail.vue b/packages/nc-gui/components/dlg/SendRecordEmail.vue
new file mode 100644
index 0000000000..c798236d6f
--- /dev/null
+++ b/packages/nc-gui/components/dlg/SendRecordEmail.vue
@@ -0,0 +1,244 @@
+<script lang="ts" setup>
+import type { TableType, ViewType } from 'nocodb-sdk'
+
+const props = defineProps<{
+ modelValue: boolean
+ meta: TableType
+ view?: ViewType
+ rowId: string
+}>()
+
+const emit = defineEmits(['update:modelValue'])
+
+const { api } = useApi()
+
+const { t } = useI18n()
+
+const { activeWorkspaceId } = storeToRefs(useWorkspace())
+
+const { activeProjectId } = storeToRefs(useBases())
+
+const { user } = useGlobal()
+
+const basesStore = useBases()
+
+const { basesUser } = storeToRefs(basesStore)
+
+const dialogShow = useVModel(props, 'modelValue', emit)
+
+const isLoading = ref(false)
+
+const selectedUserIds = ref<Set<string>>(new Set())
+
+const customMessage = ref('')
+
+const sendCopyToSelf = ref(false)
+
+const searchQuery = ref('')
+
+const baseUsers = computed(() => {
+ if (!activeProjectId.value) return []
+ return basesUser.value.get(activeProjectId.value) || []
+})
+
+const filteredUsers = computed(() => {
+ if (!searchQuery.value) return baseUsers.value
+
+ const query = searchQuery.value.toLowerCase()
+ return baseUsers.value.filter((u) => u.email?.toLowerCase().includes(query) || u.display_name?.toLowerCase().includes(query))
+})
+
+const selectedUsers = computed(() => {
+ return baseUsers.value.filter((u) => selectedUserIds.value.has(u.id))
+})
+
+const isSendButtonDisabled = computed(() => {
+ return selectedUserIds.value.size === 0
+})
+
+watch(dialogShow, (newVal) => {
+ if (newVal) {
+ selectedUserIds.value = new Set()
+ customMessage.value = ''
+ sendCopyToSelf.value = false
+ searchQuery.value = ''
+ }
+})
+
+const toggleUser = (userId: string) => {
+ if (selectedUserIds.value.has(userId)) {
+ selectedUserIds.value.delete(userId)
+ } else {
+ selectedUserIds.value.add(userId)
+ }
+ selectedUserIds.value = new Set(selectedUserIds.value)
+}
+
+const removeUser = (userId: string) => {
+ selectedUserIds.value.delete(userId)
+ selectedUserIds.value = new Set(selectedUserIds.value)
+}
+
+const sendRecord = async () => {
+ if (!activeWorkspaceId.value || !activeProjectId.value) return
+
+ try {
+ isLoading.value = true
+
+ const emails = selectedUsers.value.map((u) => u.email).filter(Boolean) as string[]
+
+ if (!emails.length) {
+ message.error(t('msg.error.atLeastOneEmail'))
+ return
+ }
+
+ await api.internal.postOperation(
+ activeWorkspaceId.value,
+ activeProjectId.value,
+ {
+ operation: 'sendRecordEmail',
+ },
+ {
+ tableId: props.meta.id,
+ viewId: props.view?.id,
+ rowId: props.rowId,
+ emails,
+ message: customMessage.value || undefined,
+ sendCopyToSelf: sendCopyToSelf.value,
+ },
+ )
+
+ message.success(t('msg.success.recordSentSuccessfully'))
+ dialogShow.value = false
+ } catch (e: any) {
+ message.error(await extractSdkResponseErrorMsg(e))
+ } finally {
+ isLoading.value = false
+ }
+}
+
+const defaultSubject = computed(() => {
+ const displayName = user.value?.display_name || user.value?.email?.split('@')[0] || 'Someone'
+ return `${displayName} shared a record from "${props.meta.title}"`
+})
+</script>
+
+<template>
+ <NcModal
+ v-model:visible="dialogShow"
+ :show-separator="false"
+ size="medium"
+ class="nc-send-record-email-dlg"
+ @keydown.esc="dialogShow = false"
+ >
+ <template #header>
+ <div class="flex flex-row text-2xl font-bold items-center gap-x-2">
+ {{ $t('activity.sendRecord') }}
+ </div>
+ </template>
+
+ <div class="flex flex-col gap-4 mt-2">
+ <div class="flex flex-col gap-1.5">
+ <label class="text-nc-content-gray text-sm font-medium">{{ $t('labels.to') }}</label>
+ <div
+ v-if="selectedUsers.length > 0"
+ class="flex flex-wrap gap-1.5 p-2 border-1 border-nc-border-gray-medium rounded-lg mb-2"
+ >
+ <div
+ v-for="selectedUser in selectedUsers"
+ :key="selectedUser.id"
+ class="flex items-center gap-1 bg-nc-bg-gray-light rounded-md px-2 py-1"
+ >
+ <GeneralUserIcon :user="selectedUser" size="medium" />
+ <span class="text-sm text-nc-content-gray capitalize truncate max-w-32">
+ {{ extractUserDisplayNameOrEmail(selectedUser) }}
+ </span>
+ <NcButton type="text" size="xxsmall" class="!p-0" @click="removeUser(selectedUser.id)">
+ <GeneralIcon icon="close" class="w-3.5 h-3.5 text-nc-content-gray-subtle2" />
+ </NcButton>
+ </div>
+ </div>
+
+ <div class="border-1 border-nc-border-gray-medium rounded-lg overflow-hidden">
+ <div class="p-2 border-b border-nc-border-gray-medium">
+ <a-input
+ v-model:value="searchQuery"
+ :placeholder="$t('placeholder.searchUsers')"
+ class="!rounded-lg"
+ :disabled="isLoading"
+ >
+ <template #prefix>
+ <GeneralIcon icon="search" class="text-nc-content-gray-muted" />
+ </template>
+ </a-input>
+ </div>
+
+ <div class="max-h-48 overflow-y-auto nc-scrollbar-md">
+ <div v-if="filteredUsers.length === 0" class="p-4 text-center text-nc-content-gray-muted text-sm">
+ {{ $t('labels.noUsersFound') }}
+ </div>
+ <div
+ v-for="baseUser in filteredUsers"
+ :key="baseUser.id"
+ class="flex items-center gap-3 px-3 py-2 hover:bg-nc-bg-gray-light cursor-pointer"
+ @click="toggleUser(baseUser.id)"
+ >
+ <NcCheckbox :checked="selectedUserIds.has(baseUser.id)" />
+ <GeneralUserIcon :user="baseUser" size="medium" />
+ <div class="flex flex-col min-w-0 flex-1">
+ <span class="text-sm text-nc-content-gray capitalize truncate">
+ {{ extractUserDisplayNameOrEmail(baseUser) }}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <span class="text-nc-content-gray-subtle2 text-xs">
+ {{ $t('msg.info.selectBaseMembers') }}
+ </span>
+ </div>
+
+ <div class="flex flex-col gap-1.5">
+ <label class="text-nc-content-gray text-sm font-medium">{{ $t('labels.subject') }}</label>
+ <div class="px-3 py-2 bg-nc-bg-gray-light rounded-lg text-nc-content-gray-subtle text-sm">
+ {{ defaultSubject }}
+ </div>
+ </div>
+
+ <div class="flex flex-col gap-1.5">
+ <label class="text-nc-content-gray text-sm font-medium">{{ $t('labels.message') }} {{ $t('labels.optional') }}</label>
+ <a-textarea
+ v-model:value="customMessage"
+ :placeholder="$t('placeholder.addPersonalMessage')"
+ :rows="3"
+ class="!rounded-lg !text-sm"
+ :disabled="isLoading"
+ />
+ </div>
+
+ <div class="flex items-center gap-2">
+ <NcCheckbox v-model:checked="sendCopyToSelf" :disabled="isLoading" />
+ <span class="text-nc-content-gray text-sm">{{ $t('labels.sendCopyToMyself') }}</span>
+ </div>
+ </div>
+
+ <div class="flex mt-6 justify-end">
+ <div class="flex gap-2">
+ <NcButton type="secondary" :disabled="isLoading" size="small" @click="dialogShow = false">
+ {{ $t('general.cancel') }}
+ </NcButton>
+ <NcButton
+ :disabled="isSendButtonDisabled || isLoading"
+ :loading="isLoading"
+ size="small"
+ type="primary"
+ class="nc-send-record-btn"
+ @click="sendRecord"
+ >
+ {{ $t('general.send') }}
+ </NcButton>
+ </div>
+ </div>
+ </NcModal>
+</template>
diff --git a/packages/nc-gui/components/smartsheet/expanded-form/index.vue b/packages/nc-gui/components/smartsheet/expanded-form/index.vue
index 41852ef7ec..2f72d134fd 100644
--- a/packages/nc-gui/components/smartsheet/expanded-form/index.vue
+++ b/packages/nc-gui/components/smartsheet/expanded-form/index.vue
@@ -729,17 +729,21 @@ function onTouchEnd() {
}
}
+const showSendRecordModal = ref(false)
+
const visibleMoreOptions = computed(() => {
const result = {
reloadRecord: !isEeUI,
copyRecordUrl: !isNew.value && !!rowId.value,
+ sendRecord: !isNew.value && !!rowId.value && !isPublic.value,
duplicateRecord: isUIAllowed('dataEdit', baseRoles.value) && !isSqlView.value && !isMobileMode.value,
deleteRecord: isUIAllowed('dataEdit', baseRoles.value) && !isSqlView.value,
}
return {
...result,
- showMoreOptionsMenu: result.reloadRecord || result.copyRecordUrl || result.duplicateRecord || result.deleteRecord,
- allHiddenExceptCopyRecordUrl: !result.reloadRecord && !result.duplicateRecord && !result.deleteRecord,
+ showMoreOptionsMenu:
+ result.reloadRecord || result.copyRecordUrl || result.sendRecord || result.duplicateRecord || result.deleteRecord,
+ allHiddenExceptCopyRecordUrl: !result.reloadRecord && !result.sendRecord && !result.duplicateRecord && !result.deleteRecord,
}
})
@@ -931,6 +935,16 @@ export default {
{{ $t('labels.copyRecordURL') }}
</div>
</NcMenuItem>
+ <NcMenuItem v-if="visibleMoreOptions.sendRecord" :disabled="isLoading" @click="showSendRecordModal = true">
+ <div
+ v-e="['c:row-expand:send-record']"
+ data-testid="nc-expanded-form-send-record"
+ class="flex gap-2 items-center"
+ >
+ <GeneralIcon icon="mail" class="cursor-pointer" />
+ {{ $t('activity.sendRecord') }}
+ </div>
+ </NcMenuItem>
<NcTooltip v-if="visibleMoreOptions.duplicateRecord && meta?.synced" placement="left">
<template #title>
{{ $t('msg.info.duplicateNotAvailableForSyncedTable') }}
@@ -1096,6 +1110,13 @@ export default {
</div>
</div>
</NcModal>
+ <DlgSendRecordEmail
+ v-if="visibleMoreOptions.sendRecord && primaryKey"
+ v-model="showSendRecordModal"
+ :meta="meta"
+ :view="view"
+ :row-id="primaryKey"
+ />
</template>
<style lang="scss">
diff --git a/packages/nc-gui/lang/en.json b/packages/nc-gui/lang/en.json
index 24e9425c3c..ecf4898a82 100644
--- a/packages/nc-gui/lang/en.json
+++ b/packages/nc-gui/lang/en.json
@@ -273,6 +273,7 @@
"whatsappTwilio": "WhatsApp Twilio",
"quote": "Quote",
"submit": "Submit",
+ "send": "Send",
"create": "Create",
"createEntity": "Create {entity}",
"creating": "Creating",
@@ -1396,6 +1397,9 @@
"copiedRecordURL": "Copied Record URL",
"copyRecordURL": "Copy Record URL",
"duplicateRecord": "Duplicate record",
+ "to": "To",
+ "message": "Message",
+ "sendCopyToMyself": "Send a copy to myself",
"binaryEncodingFormat": "Binary encoding format",
"syntax": "Syntax",
"examples": "Examples",
@@ -1594,6 +1598,7 @@
"importFormulaColumns": "Import formula columns",
"importUsers": "Import Users (by email)",
"noData": "No Data",
+ "noUsersFound": "No users found",
"goToDashboard": "Go to Dashboard",
"importing": "Importing",
"importingFromAirtable": "Importing from Airtable",
@@ -1934,6 +1939,7 @@
"setDisplay": "Set as display value",
"addRow": "Add new record",
"saveRow": "Save record",
+ "sendRecord": "Send Record",
"saveAndExit": "Save & Exit",
"saveAndStay": "Save & Stay",
"insertRow": "Insert new record",
@@ -2228,6 +2234,9 @@
"confirm": "Confirm new password"
},
"selectAColumnForTheQRCodeValue": "Select a field for the QR code value",
+ "enterEmailAddresses": "Enter email addresses",
+ "addPersonalMessage": "Add a personal message (optional)",
+ "searchUsers": "Search users",
"allowNegativeNumbers": "Allow negative numbers",
"searchProjectTree": "Search tables",
"searchFields": "Search fields",
@@ -2473,6 +2482,8 @@
"cantDeleteLastSyncSource": "Cannot delete last sync source",
"cantDeleteLastGridView": "You can't delete a view when it's the only collaborative grid view in the table",
"inviteSent": "Invitation sent successfully",
+ "separateEmailsWithComma": "Separate multiple email addresses with commas. Maximum 15 recipients.",
+ "selectBaseMembers": "Select base members to send the record to",
"userRoleUpdated": "User role updated successfully",
"teamRoleUpdated": "Team role updated successfully",
"actionIrreversible": "This action is irreversible",
@@ -2748,6 +2759,7 @@
"invalidXml": "Invalid XML",
"invalidURL": "Invalid URL",
"invalidEmail": "Invalid Email",
+ "atLeastOneEmail": "At least one email address is required",
"internalError": "Some internal error occurred",
"templateGeneratorNotFound": "Template Generator cannot be found!",
"fileUploadFailed": "Failed to upload file",
@@ -2886,6 +2898,7 @@
"userAddedToProject": "Successfully added user to base",
"userAdded": "Successfully added user",
"userDeletedFromProject": "Successfully deleted user from base",
+ "recordSentSuccessfully": "Record sent successfully",
"inviteEmailSent": "Invite Email sent successfully",
"baseInstalled": "Base installed successfully",
"inviteURLCopied": "Invite URL copied to clipboard",
diff --git a/packages/nocodb/src/controllers/internal/modules/SendRecordEmail.operations.ts b/packages/nocodb/src/controllers/internal/modules/SendRecordEmail.operations.ts
new file mode 100644
index 0000000000..1003765097
--- /dev/null
+++ b/packages/nocodb/src/controllers/internal/modules/SendRecordEmail.operations.ts
@@ -0,0 +1,238 @@
+import { Injectable } from '@nestjs/common';
+import { isSystemColumn, UITypes, ColumnHelper } from 'nocodb-sdk';
+import type { ColumnType, NcContext, NcRequest, TableType } from 'nocodb-sdk';
+import type { OPERATION_SCOPES } from '~/controllers/internal/operationScopes';
+import type {
+ InternalApiModule,
+ InternalPOSTResponseType,
+} from '~/utils/internal-type';
+import { MailService } from '~/services/mail/mail.service';
+import { MailEvent } from '~/interface/Mail';
+import { Base, BaseUser, Model, Source } from '~/models';
+import { NcError } from '~/helpers/catchError';
+import { extractDisplayNameFromEmail } from '~/utils';
+import { DataTableService } from '~/services/data-table.service';
+
+interface SendRecordEmailPayload {
+ tableId: string;
+ viewId?: string;
+ rowId: string;
+ emails: string[];
+ message?: string;
+ sendCopyToSelf?: boolean;
+}
+
+@Injectable()
+export class SendRecordEmailOperations
+ implements InternalApiModule<InternalPOSTResponseType>
+{
+ constructor(
+ protected readonly mailService: MailService,
+ protected readonly dataTableService: DataTableService,
+ ) {}
+
+ operations = ['sendRecordEmail' as const];
+ httpMethod = 'POST' as const;
+
+ async handle(
+ context: NcContext,
+ {
+ payload,
+ operation,
+ req,
+ }: {
+ workspaceId: string;
+ baseId: string;
+ operation: keyof typeof OPERATION_SCOPES;
+ payload: SendRecordEmailPayload;
+ req: NcRequest;
+ },
+ ): InternalPOSTResponseType {
+ switch (operation) {
+ case 'sendRecordEmail':
+ return await this.sendRecordEmail(context, payload, req);
+ }
+ }
+
+ private async sendRecordEmail(
+ context: NcContext,
+ payload: SendRecordEmailPayload,
+ req: NcRequest,
+ ) {
+ const { tableId, viewId, rowId, emails, message, sendCopyToSelf } = payload;
+
+ if (!emails || emails.length === 0) {
+ NcError.get(context).badRequest(
+ 'At least one recipient email is required',
+ );
+ }
+
+ if (emails.length > 15) {
+ NcError.get(context).badRequest('Maximum 15 recipients allowed');
+ }
+
+ const user = req.user;
+ const senderName = extractDisplayNameFromEmail(
+ user.email,
+ user.display_name,
+ );
+ const senderEmail = user.email;
+
+ const model = await Model.get(context, tableId);
+ if (!model) {
+ NcError.get(context).tableNotFound(tableId);
+ }
+
+ const base = await Base.get(context, model.base_id);
+
+ const baseUsers = await BaseUser.getUsersList(context, {
+ base_id: base.id,
+ mode: 'full',
+ });
+
+ const baseUserEmails = baseUsers.map((u) => u.email?.toLowerCase());
+
+ const finalEmails = [...emails];
+ if (sendCopyToSelf && senderEmail && !finalEmails.includes(senderEmail)) {
+ if (baseUserEmails.includes(senderEmail.toLowerCase())) {
+ finalEmails.push(senderEmail);
+ }
+ }
+
+ const invalidEmails: string[] = [];
+ for (const email of finalEmails) {
+ if (!baseUserEmails.includes(email.toLowerCase())) {
+ invalidEmails.push(email);
+ }
+ }
+
+ if (invalidEmails.length > 0) {
+ NcError.get(context).badRequest(
+ `The following email(s) are not members of this base: ${invalidEmails.join(', ')}`,
+ );
+ }
+
+ const row = await this.dataTableService.dataRead(context, {
+ baseId: context.base_id,
+ modelId: tableId,
+ rowId,
+ viewId,
+ query: {},
+ });
+
+ if (!row) {
+ NcError.get(context).recordNotFound(rowId);
+ }
+
+ const source = await Source.get(context, model.source_id);
+ const columns = await model.getColumns(context);
+
+ const filteredColumns = columns.filter(
+ (col: ColumnType) =>
+ !isSystemColumn(col) &&
+ col.uidt !== UITypes.QrCode &&
+ col.uidt !== UITypes.Barcode,
+ );
+
+ const models = await source.getModels(context);
+ const metas = models.reduce(
+ (o: Record<string, TableType>, m: TableType) => {
+ return Object.assign(o, { [m.id]: m });
+ },
+ {},
+ );
+
+ const recordData = this.transformDataForEmail(
+ row,
+ filteredColumns,
+ source,
+ model,
+ metas,
+ );
+
+ const result = await this.mailService.sendMail({
+ mailEvent: MailEvent.SEND_RECORD,
+ payload: {
+ senderName,
+ senderEmail,
+ emails: finalEmails,
+ model,
+ base,
+ message,
+ recordData,
+ rowId,
+ req,
+ },
+ });
+
+ if (!result) {
+ NcError.get(context).internalServerError(
+ 'Failed to send email. Please check your email configuration.',
+ );
+ }
+
+ return { msg: 'Record sent successfully' };
+ }
+
+ private transformDataForEmail(
+ data: Record<string, any>,
+ columns: ColumnType[],
+ source: Source,
+ model: Model,
+ models: Record<string, TableType>,
+ ): Array<{
+ parsedValue?: any;
+ columnTitle: string;
+ uidt: UITypes | string;
+ }> {
+ const transformedData: Array<{
+ parsedValue?: any;
+ columnTitle: string;
+ uidt: UITypes | string;
+ }> = [];
+
+ for (const col of columns) {
+ let serializedValue: string | undefined;
+
+ try {
+ serializedValue = ColumnHelper.parsePlainCellValue(data[col.title], {
+ col,
+ isMysql: () => source.type.startsWith('mysql'),
+ isPg: () => source.type === 'pg',
+ isXcdbBase: () => !!source.isMeta(),
+ meta: model,
+ metas: models,
+ });
+
+ if (col.uidt === UITypes.Attachment) {
+ let attachments = data[col.title] || [];
+ if (typeof data[col.title] === 'string') {
+ try {
+ attachments = JSON.parse(data[col.title]);
+ } catch {
+ attachments = [];
+ }
+ }
+ serializedValue = Array.isArray(attachments)
+ ? attachments
+ .map((attachment: any) => attachment?.title || '')
+ .filter(Boolean)
+ .join(', ')
+ : '';
+ }
+ } catch {
+ serializedValue = data[col.title]?.toString() || '';
+ }
+
+ if (serializedValue !== undefined && serializedValue !== '') {
+ transformedData.push({
+ parsedValue: serializedValue,
+ uidt: col.uidt,
+ columnTitle: col.title,
+ });
+ }
+ }
+
+ return transformedData;
+ }
+}
diff --git a/packages/nocodb/src/controllers/internal/operationScopes.ts b/packages/nocodb/src/controllers/internal/operationScopes.ts
index 17fe62803c..46cc405045 100644
--- a/packages/nocodb/src/controllers/internal/operationScopes.ts
+++ b/packages/nocodb/src/controllers/internal/operationScopes.ts
@@ -143,4 +143,7 @@ export const OPERATION_SCOPES = {
managedAppDeployments: 'base',
managedAppVersionDeployments: 'base',
managedAppDeploymentLogs: 'base',
+
+ // Send Record Email
+ sendRecordEmail: 'base',
} as const;
diff --git a/packages/nocodb/src/controllers/internal/provider.ts b/packages/nocodb/src/controllers/internal/provider.ts
index c0febd2902..3381cce7f6 100644
--- a/packages/nocodb/src/controllers/internal/provider.ts
+++ b/packages/nocodb/src/controllers/internal/provider.ts
@@ -7,6 +7,7 @@ import { OAuthPostOperations } from '~/controllers/internal/modules/OAuthPost.op
import { DependencyPostOperations } from '~/controllers/internal/modules/DependencyPost.operations';
import { UiGetOperations } from '~/controllers/internal/modules/UiGet.operations';
import { UiPostOperations } from '~/controllers/internal/modules/UiPost.operations';
+import { SendRecordEmailOperations } from '~/controllers/internal/modules/SendRecordEmail.operations';
import { INTERNAL_API_MODULE_PROVIDER_KEY } from '~/utils/internal-type';
export const InternalApiModules = [
@@ -18,6 +19,7 @@ export const InternalApiModules = [
DependencyPostOperations,
UiGetOperations,
UiPostOperations,
+ SendRecordEmailOperations,
];
export const InternalApiModuleProvider = {
diff --git a/packages/nocodb/src/helpers/webhookHelpers.ts b/packages/nocodb/src/helpers/webhookHelpers.ts
index 3c9930e9fc..a1c19e3031 100644
--- a/packages/nocodb/src/helpers/webhookHelpers.ts
+++ b/packages/nocodb/src/helpers/webhookHelpers.ts
@@ -512,7 +512,7 @@ export function transformDataForMailRendering(
let serializedValue: string | undefined;
try {
- serializedValue = ColumnHelper.serializeValue(data[col.title], {
+ serializedValue = ColumnHelper.parsePlainCellValue(data[col.title], {
col,
isMysql: () => source.type.startsWith('mysql'),
isPg: () => source.type === 'pg',
diff --git a/packages/nocodb/src/interface/Mail.ts b/packages/nocodb/src/interface/Mail.ts
index bac1769911..38c8876880 100644
--- a/packages/nocodb/src/interface/Mail.ts
+++ b/packages/nocodb/src/interface/Mail.ts
@@ -35,6 +35,8 @@ enum MailEvent {
WORKSPACE_TEAM_ROLE_UPDATE = 'WORKSPACE_TEAM_ROLE_UPDATE',
BASE_TEAM_REMOVED = 'BASE_TEAM_REMOVED',
BASE_TEAM_ROLE_UPDATE = 'BASE_TEAM_ROLE_UPDATE',
+ WORKFLOW_ERROR_DIGEST = 'WORKFLOW_ERROR_DIGEST',
+ SEND_RECORD = 'SEND_RECORD',
}
interface CommentPayload {
@@ -102,6 +104,22 @@ interface FormSubmissionPayload {
}[];
}
+interface SendRecordPayload {
+ senderName: string;
+ senderEmail: string;
+ emails: string[];
+ model: TableType;
+ base: BaseType;
+ message?: string;
+ recordData: {
+ parsedValue?: any;
+ columnTitle: string;
+ uidt: UITypes | string;
+ }[];
+ rowId: string;
+ req: NcRequest;
+}
+
type MailParams =
| {
mailEvent: MailEvent.COMMENT_CREATE | MailEvent.COMMENT_UPDATE;
@@ -138,6 +156,10 @@ type MailParams =
| {
mailEvent: MailEvent.FORM_SUBMISSION;
payload: FormSubmissionPayload;
+ }
+ | {
+ mailEvent: MailEvent.SEND_RECORD;
+ payload: SendRecordPayload;
};
interface RawMailParams {
@@ -150,4 +172,10 @@ interface RawMailParams {
bcc?: string | string[];
}
-export { MailEvent, MailParams, FormSubmissionPayload, RawMailParams };
+export {
+ MailEvent,
+ MailParams,
+ FormSubmissionPayload,
+ SendRecordPayload,
+ RawMailParams,
+};
diff --git a/packages/nocodb/src/services/mail/mail.service.ts b/packages/nocodb/src/services/mail/mail.service.ts
index 2eb3dafbbe..7219fe53cc 100644
--- a/packages/nocodb/src/services/mail/mail.service.ts
+++ b/packages/nocodb/src/services/mail/mail.service.ts
@@ -291,6 +291,42 @@ export class MailService {
});
}
break;
+ case MailEvent.SEND_RECORD:
+ {
+ const {
+ senderName,
+ senderEmail,
+ emails,
+ model,
+ base,
+ message,
+ recordData,
+ rowId,
+ req,
+ } = payload;
+
+ const recordUrl = this.buildUrl(req, {
+ workspaceId: base.fk_workspace_id,
+ baseId: base.id,
+ tableId: model.id,
+ rowId,
+ });
+
+ await mailerAdapter.mailSend({
+ to: emails.join(','),
+ subject: `${senderName} shared a record from "${model.title}"`,
+ html: await this.renderMail('SendRecord', {
+ senderName,
+ senderEmail,
+ tableTitle: model.title,
+ baseTitle: base.title,
+ message,
+ recordData,
+ recordUrl,
+ }),
+ });
+ }
+ break;
}
return true;
} catch (e) {
diff --git a/packages/nocodb/src/services/mail/templates/index.ts b/packages/nocodb/src/services/mail/templates/index.ts
index 7854adddee..1d14794ff5 100644
--- a/packages/nocodb/src/services/mail/templates/index.ts
+++ b/packages/nocodb/src/services/mail/templates/index.ts
@@ -6,6 +6,7 @@ import OrganizationInvite from '~/services/mail/templates/org-invite';
import OrganizationRoleUpdate from '~/services/mail/templates/org-role-update';
import BaseRoleUpdate from '~/services/mail/templates/base-role-update';
import FormSubmission from '~/services/mail/templates/form-submission';
+import SendRecord from '~/services/mail/templates/send-record';
export {
Welcome,
@@ -16,4 +17,5 @@ export {
OrganizationInvite,
OrganizationRoleUpdate,
FormSubmission,
+ SendRecord,
};
diff --git a/packages/nocodb/src/services/mail/templates/send-record.tsx b/packages/nocodb/src/services/mail/templates/send-record.tsx
new file mode 100644
index 0000000000..100fc882d0
--- /dev/null
+++ b/packages/nocodb/src/services/mail/templates/send-record.tsx
@@ -0,0 +1,200 @@
+import {
+ Body,
+ Column,
+ Head,
+ Heading,
+ Hr,
+ Html,
+ Img,
+ Preview,
+ Row,
+ Section,
+ Text,
+} from '@react-email/components';
+import * as React from 'react';
+import { UITypes } from 'nocodb-sdk';
+import {
+ ContentWrapper,
+ Footer,
+ RootWrapper,
+} from '~/services/mail/templates/components';
+import { NC_EMAIL_ASSETS_BASE_URL } from '~/constants';
+
+interface SendRecordTemplateProps {
+ senderName: string;
+ senderEmail: string;
+ tableTitle: string;
+ baseTitle: string;
+ message?: string;
+ recordData: Array<{
+ parsedValue?: any;
+ columnTitle: string;
+ uidt: UITypes | string;
+ }>;
+ recordUrl?: string;
+}
+
+const SendRecord = ({
+ senderName,
+ senderEmail,
+ tableTitle,
+ baseTitle,
+ message,
+ recordData,
+ recordUrl,
+}: SendRecordTemplateProps) => (
+ <Html>
+ <RootWrapper>
+ <Head />
+ <Preview>
+ {senderName} shared a record from {tableTitle}
+ </Preview>
+ <Body className="bg-white">
+ <ContentWrapper disableContainerPadding>
+ <Section className="p-6 mx-auto">
+ <Heading className="text-gray-900 text-center font-bold m-auto text-xl md:text-2xl">
+ {senderName} shared a record with you
+ </Heading>
+
+ <Section
+ align="center"
+ className="my-6"
+ style={{ textAlign: 'center', lineHeight: '28px' }}
+ >
+ <table
+ cellPadding="0"
+ cellSpacing="0"
+ style={{ display: 'inline-block', verticalAlign: 'middle' }}
+ >
+ <tr>
+ <td style={{ paddingRight: '8px', verticalAlign: 'middle' }}>
+ <Img
+ src={`${NC_EMAIL_ASSETS_BASE_URL}/icons/table.png`}
+ alt="Table Icon"
+ height={24}
+ width={24}
+ className="!h-6 inline-block"
+ style={{ verticalAlign: 'middle' }}
+ />
+ </td>
+ <td style={{ verticalAlign: 'middle' }}>
+ <span
+ className="text-base font-bold mt-0.5 text-gray-900"
+ style={{
+ verticalAlign: 'middle',
+ display: 'inline-block',
+ lineHeight: '28px',
+ }}
+ >
+ {tableTitle}
+ </span>
+ </td>
+ </tr>
+ </table>
+ </Section>
+
+ <Text className="text-center font-weight-thin text-gray-600 !my-0">
+ <span className="font-bold text-gray-800">{senderName}</span> (
+ {senderEmail}) has shared a record from
+ <span className="font-bold text-gray-800"> {tableTitle} </span>
+ in
+ <span className="font-bold text-gray-800"> {baseTitle}</span>.
+ </Text>
+
+ {message && (
+ <Section className="mt-6 p-4 bg-gray-50 rounded-lg">
+ <Text className="text-gray-700 !my-0 italic">"{message}"</Text>
+ </Section>
+ )}
+ </Section>
+
+ <Hr />
+
+ <Section className="p-6 mx-auto">
+ <Text className="text-lg font-bold text-center !my-0">
+ Record Details
+ </Text>
+ <Section>
+ {recordData.map((field) => (
+ <Section className="mt-6" key={field.columnTitle}>
+ <Row>
+ <Column className="flex align-middle items-center">
+ <Img
+ className="align-middle"
+ width={16}
+ height={16}
+ src={`${NC_EMAIL_ASSETS_BASE_URL}/icons/${field.uidt}.png`}
+ />
+ <Section className="!ml-2 truncate inline-block text-[13px] !my-0 !mr-0 leading-4.5 text-gray-600 align-middle">
+ {field.columnTitle}
+ </Section>
+ </Column>
+ </Row>
+ <Row
+ className="px-4 py-2 border border-1 mt-2 border-solid rounded-lg border-gray-200"
+ style={{
+ boxShadow: `0px 0px 4px 0px rgba(0, 0, 0, 0.08)`,
+ }}
+ >
+ <Column>
+ <Text className="text-gray-800 max-w-xs truncate !my-0">
+ {field.parsedValue || '-'}
+ </Text>
+ </Column>
+ </Row>
+ </Section>
+ ))}
+ </Section>
+
+ {recordUrl && (
+ <Section className="mt-8 text-center">
+ <a
+ href={recordUrl}
+ className="inline-block px-6 py-3 bg-blue-600 text-white font-semibold rounded-lg no-underline"
+ style={{
+ backgroundColor: '#3366FF',
+ color: '#ffffff',
+ padding: '12px 24px',
+ borderRadius: '8px',
+ textDecoration: 'none',
+ }}
+ >
+ View Record in NocoDB
+ </a>
+ </Section>
+ )}
+ </Section>
+ </ContentWrapper>
+ <Footer />
+ </Body>
+ </RootWrapper>
+ </Html>
+);
+
+SendRecord.PreviewProps = {
+ senderName: 'John Doe',
+ senderEmail: '[email protected]',
+ tableTitle: 'Contacts',
+ baseTitle: 'My Base',
+ message: "Here's the contact information you requested.",
+ recordData: [
+ {
+ parsedValue: 'Jane Smith',
+ uidt: UITypes.SingleLineText,
+ columnTitle: 'Name',
+ },
+ {
+ parsedValue: '[email protected]',
+ uidt: UITypes.Email,
+ columnTitle: 'Email',
+ },
+ {
+ parsedValue: '+1 234 567 8900',
+ uidt: UITypes.PhoneNumber,
+ columnTitle: 'Phone',
+ },
+ ],
+ recordUrl: 'https://app.nocodb.com/#/workspace/base/table?rowId=123',
+};
+
+export default SendRecord;
diff --git a/packages/nocodb/src/utils/acl.ts b/packages/nocodb/src/utils/acl.ts
index 783756530c..951257a016 100644
--- a/packages/nocodb/src/utils/acl.ts
+++ b/packages/nocodb/src/utils/acl.ts
@@ -207,6 +207,9 @@ const permissionScopes = {
'mcpCreate',
'mcpUpdate',
'mcpDelete',
+
+ // Send record email
+ 'sendRecordEmail',
],
};
@@ -291,6 +294,12 @@ const rolePermissions:
mcpCreate: true,
mcpUpdate: true,
mcpDelete: true,
+
+ // etc
+ fetchViaUrl: true,
+
+ // Send record email
+ sendRecordEmail: true,
},
},
[ProjectRoles.COMMENTER]: {