Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

custom display name support for campaign from addresses

Pedro Ladeira25c56952fe4b
diff --git a/apps/web/app/(ee)/api/campaigns/[campaignId]/preview/route.ts b/apps/web/app/(ee)/api/campaigns/[campaignId]/preview/route.ts
index 41d3eb9281..a5c289bce0 100644
--- a/apps/web/app/(ee)/api/campaigns/[campaignId]/preview/route.ts
+++ b/apps/web/app/(ee)/api/campaigns/[campaignId]/preview/route.ts
@@ -5,8 +5,15 @@ import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-progr
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
+import {
+ parseCampaignFromAddress,
+ resolveCampaignFromAddress,
+} from "@/lib/email/parse-campaign-from-address";
import { TiptapNode } from "@/lib/types";
-import { CampaignSchema } from "@/lib/zod/schemas/campaigns";
+import {
+ CampaignSchema,
+ campaignFromSchema,
+} from "@/lib/zod/schemas/campaigns";
import { sendBatchEmail } from "@dub/email";
import CampaignEmail from "@dub/email/templates/campaign-email";
import { NextResponse } from "next/server";
@@ -17,7 +24,7 @@ const sendPreviewEmailSchema = CampaignSchema.pick({
preview: true,
bodyJson: true,
}).extend({
- from: z.email().optional(),
+ from: campaignFromSchema.optional(),
emailAddresses: z
.array(z.email())
.min(1)
@@ -54,23 +61,33 @@ export const POST = withWorkspace(
]);
// check if from email is a valid email domain
- if (
- from &&
- !program.emailDomains.some(
- ({ slug: emailDomain }) => from.split("@")[1] === emailDomain,
- )
- ) {
- throw new DubApiError({
- code: "bad_request",
- message: "Invalid `from` email address.",
- });
+ if (from) {
+ const parsed = parseCampaignFromAddress(from);
+ const domainPart = parsed?.email.split("@")[1];
+
+ if (
+ !parsed ||
+ !program.emailDomains.some(
+ ({ slug: emailDomain }) => domainPart === emailDomain,
+ )
+ ) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Invalid domain. You can only send from a verified domain.",
+ });
+ }
}
const { data, error } = await sendBatchEmail(
emailAddresses.map((email) => ({
variant: campaign.type === "marketing" ? "marketing" : "notifications",
to: email,
- ...(from && { from: `${program.name} <${from}>` }),
+ ...(from && {
+ from: resolveCampaignFromAddress({
+ from,
+ programName: program.name,
+ }),
+ }),
...(program.supportEmail ? { replyTo: program.supportEmail } : {}),
subject: `[TEST] ${subject}`,
react: CampaignEmail({
diff --git a/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts b/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
index 117c8e5e04..31c8c3a767 100644
--- a/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
+++ b/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
@@ -4,6 +4,7 @@ import { createId } from "@/lib/api/create-id";
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { qstash } from "@/lib/cron";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { resolveCampaignFromAddress } from "@/lib/email/parse-campaign-from-address";
import { constructPartnerLink } from "@/lib/partners/construct-partner-link";
import { prisma } from "@/lib/prisma";
import { TiptapNode } from "@/lib/types";
@@ -249,7 +250,10 @@ export async function POST(req: Request) {
const { data, error } = await sendBatchEmail(
partnerUsersChunk.map((partnerUser) => ({
- from: `${program.name} <${campaign.from}>`,
+ from: resolveCampaignFromAddress({
+ from: campaign.from!,
+ programName: program.name,
+ }),
to: partnerUser.email!,
subject: campaign.subject,
...(program.supportEmail ? { replyTo: program.supportEmail } : {}),
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-controls.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-controls.tsx
index 7b5dd3203b..beb654c416 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-controls.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-controls.tsx
@@ -2,6 +2,7 @@ import { mutatePrefix } from "@/lib/swr/mutate";
import { useApiMutation } from "@/lib/swr/use-api-mutation";
import useWorkspace from "@/lib/swr/use-workspace";
import { Campaign } from "@/lib/types";
+import { campaignFromSchema } from "@/lib/zod/schemas/campaigns";
import { ThreeDots } from "@/ui/shared/icons";
import {
Button,
@@ -92,6 +93,13 @@ export function CampaignControls({ campaign }: CampaignControlsProps) {
return "Please select a sender email address.";
}
+ if (from) {
+ const fromResult = campaignFromSchema.safeParse(from);
+ if (!fromResult.success) {
+ return "Please enter a valid sender name and email address.";
+ }
+ }
+
if (
!sendPreview &&
campaign.type === "transactional" &&
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx
index 7779e4245a..14ded83a7f 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx
@@ -1,7 +1,12 @@
import { uploadCampaignImageAction } from "@/lib/actions/partners/upload-campaign-image";
import { CAMPAIGN_READONLY_STATUSES } from "@/lib/api/campaigns/constants";
+import {
+ formatCampaignFromAddress,
+ parseCampaignFromAddress,
+} from "@/lib/email/parse-campaign-from-address";
import { useApiMutation } from "@/lib/swr/use-api-mutation";
import { useEmailDomains } from "@/lib/swr/use-email-domains";
+import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
import { Campaign, UpdateCampaignFormData } from "@/lib/types";
import { EMAIL_TEMPLATE_VARIABLES } from "@/lib/zod/schemas/campaigns";
@@ -23,6 +28,7 @@ import {
} from "@dub/ui";
import { capitalize, cn } from "@dub/utils";
import { CampaignStatus } from "@prisma/client";
+import slugify from "@sindresorhus/slugify";
import { motion } from "motion/react";
import { useAction } from "next-safe-action/hooks";
import Link from "next/link";
@@ -86,9 +92,114 @@ const statusMessages = {
canceled: "Edits aren't allowed after cancellation.",
};
+function CampaignFromField({
+ value,
+ onChange,
+ disabled,
+ domainSlug,
+ displayNamePlaceholder,
+}: {
+ value: string | undefined;
+ onChange: (value: string | undefined) => void;
+ disabled: boolean;
+ domainSlug: string | undefined;
+ displayNamePlaceholder: string;
+}) {
+ const parsed = value ? parseCampaignFromAddress(value) : null;
+ const [displayName, setDisplayName] = useState(parsed?.displayName ?? "");
+ const [localPart, setLocalPart] = useState(
+ parsed?.email?.split("@")[0] ?? "",
+ );
+ const localPartMeasureRef = useRef<HTMLSpanElement>(null);
+ const [localPartWidth, setLocalPartWidth] = useState(0);
+
+ useEffect(() => {
+ if (!value) return;
+
+ const next = parseCampaignFromAddress(value);
+ if (!next) return;
+
+ setDisplayName(next.displayName ?? "");
+ setLocalPart(next.email.split("@")[0] ?? "");
+ }, [value]);
+
+ useEffect(() => {
+ if (!localPartMeasureRef.current) return;
+
+ setLocalPartWidth(localPartMeasureRef.current.scrollWidth);
+ }, [localPart]);
+
+ const commit = (nextDisplayName: string, nextLocalPart: string) => {
+ setDisplayName(nextDisplayName);
+ setLocalPart(nextLocalPart);
+
+ if (!domainSlug) return;
+
+ if (!nextLocalPart.trim()) {
+ onChange(undefined);
+ return;
+ }
+
+ onChange(
+ formatCampaignFromAddress({
+ displayName: nextDisplayName.trim() || null,
+ email: `${nextLocalPart.trim()}@${domainSlug}`,
+ }),
+ );
+ };
+
+ return (
+ <div
+ className={`flex items-center gap-1 ${inputClassName} ${disabled ? "cursor-not-allowed opacity-80" : ""}`}
+ >
+ <input
+ type="text"
+ placeholder={displayNamePlaceholder}
+ className="text-content-default placeholder:text-content-muted min-w-0 flex-1 border-0 bg-transparent p-0 focus:outline-none focus:ring-0 sm:text-sm"
+ disabled={disabled}
+ value={displayName}
+ onChange={(e) => {
+ const nextDisplayName = e.target.value;
+ commit(nextDisplayName, slugify(nextDisplayName));
+ }}
+ aria-label="From display name"
+ />
+ <span className="text-content-subtle shrink-0 text-sm" aria-hidden>
+ &lt;
+ </span>
+ <div className="relative flex min-w-0 shrink-0 items-center">
+ <span
+ ref={localPartMeasureRef}
+ className="pointer-events-none invisible absolute whitespace-pre text-sm"
+ aria-hidden
+ >
+ {localPart || "address"}
+ </span>
+ <input
+ type="text"
+ placeholder="address"
+ style={{ width: Math.max(localPartWidth, 1) }}
+ className="text-content-default placeholder:text-content-muted m-0 max-w-[12rem] border-0 bg-transparent p-0 text-sm leading-none focus:outline-none focus:ring-0"
+ disabled={disabled}
+ value={localPart}
+ onChange={(e) => commit(displayName, e.target.value)}
+ aria-label="From email address"
+ />
+ <span className="text-content-default shrink-0 text-sm leading-none">
+ {domainSlug ? `@${domainSlug}` : ""}
+ </span>
+ </div>
+ <span className="text-content-subtle shrink-0 text-sm" aria-hidden>
+ &gt;
+ </span>
+ </div>
+ );
+}
+
export function CampaignEditor({ campaign }: { campaign: Campaign }) {
const { id: workspaceId, slug: workspaceSlug } = useWorkspace();
const { verifiedEmailDomain } = useEmailDomains();
+ const { program } = useProgram();
const isActive = campaign.status === CampaignStatus.active;
const isReadOnly = CAMPAIGN_READONLY_STATUSES.includes(campaign.status);
@@ -328,10 +439,6 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
control={control}
name="from"
render={({ field }) => {
- const localPart = field.value?.split("@")[0] || "";
- const domainSuffix = verifiedEmailDomain?.slug
- ? `@${verifiedEmailDomain.slug}`
- : "";
const isDisabled = isReadOnly || !verifiedEmailDomain;
return (
@@ -351,28 +458,13 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
disabled={isDisabled}
hideIcon={true}
>
- <div
- className={`flex items-center gap-1 ${inputClassName} ${isDisabled ? "cursor-not-allowed opacity-80" : ""}`}
- >
- <input
- type="text"
- placeholder="Address"
- className="text-content-default placeholder:text-content-muted min-w-0 flex-1 border-0 bg-transparent p-0 focus:outline-none focus:ring-0 sm:text-sm"
- disabled={isDisabled}
- value={localPart}
- onChange={(e) => {
- const newLocalPart = e.target.value;
- if (verifiedEmailDomain?.slug) {
- field.onChange(
- `${newLocalPart}@${verifiedEmailDomain.slug}`,
- );
- }
- }}
- />
- <span className="text-content-muted shrink-0 text-sm">
- {domainSuffix}
- </span>
- </div>
+ <CampaignFromField
+ value={field.value}
+ onChange={field.onChange}
+ disabled={isDisabled}
+ domainSlug={verifiedEmailDomain?.slug}
+ displayNamePlaceholder={program?.name || "Display name"}
+ />
</DisabledInputWrapper>
);
}}
diff --git a/apps/web/lib/api/campaigns/validate-campaign.ts b/apps/web/lib/api/campaigns/validate-campaign.ts
index afef3332f2..9e628a595d 100644
--- a/apps/web/lib/api/campaigns/validate-campaign.ts
+++ b/apps/web/lib/api/campaigns/validate-campaign.ts
@@ -1,3 +1,4 @@
+import { parseCampaignFromAddress } from "@/lib/email/parse-campaign-from-address";
import { prisma } from "@/lib/prisma";
import { updateCampaignSchema } from "@/lib/zod/schemas/campaigns";
import { Campaign, EmailDomain } from "@prisma/client";
@@ -98,16 +99,16 @@ export function validateCampaignFromAddress({
});
}
- const parts = campaign.from.split("@");
+ const parsed = parseCampaignFromAddress(campaign.from);
- if (parts.length !== 2) {
+ if (!parsed) {
throw new DubApiError({
code: "bad_request",
message: `Campaign (${campaign.id}) has an invalid email address format for 'from' field.`,
});
}
- const domainPart = parts[1];
+ const domainPart = parsed.email.split("@")[1];
const emailDomain = emailDomains.find(
(emailDomain) => emailDomain.slug === domainPart,
diff --git a/apps/web/lib/api/workflows/send-campaign/execute.ts b/apps/web/lib/api/workflows/send-campaign/execute.ts
index 12b363c710..cfc4ba5234 100644
--- a/apps/web/lib/api/workflows/send-campaign/execute.ts
+++ b/apps/web/lib/api/workflows/send-campaign/execute.ts
@@ -1,5 +1,6 @@
import { evaluateWorkflowConditions } from "@/lib/api/workflows/evaluate-workflow-conditions";
import { WorkflowCondition, WorkflowContext } from "@/lib/api/workflows/types";
+import { resolveCampaignFromAddress } from "@/lib/email/parse-campaign-from-address";
import { aggregatePartnerLinksStats } from "@/lib/partners/aggregate-partner-links-stats";
import { constructPartnerLink } from "@/lib/partners/construct-partner-link";
import { prisma } from "@/lib/prisma";
@@ -153,7 +154,14 @@ export const executeSendCampaignWorkflow = async ({
const { data } = await sendBatchEmail(
partnerUsers.map((partnerUser) => ({
variant: "notifications",
- ...(campaign.from ? { from: campaign.from } : {}),
+ ...(campaign.from
+ ? {
+ from: resolveCampaignFromAddress({
+ from: campaign.from,
+ programName: program.name,
+ }),
+ }
+ : {}),
to: partnerUser.email!,
subject: campaign.subject,
replyTo: program.supportEmail || "noreply",
diff --git a/apps/web/lib/email/parse-campaign-from-address.ts b/apps/web/lib/email/parse-campaign-from-address.ts
new file mode 100644
index 0000000000..6b944395d3
--- /dev/null
+++ b/apps/web/lib/email/parse-campaign-from-address.ts
@@ -0,0 +1,65 @@
+import * as z from "zod/v4";
+
+type ParsedCampaignFromAddress = {
+ displayName: string | null;
+ email: string;
+};
+
+export function parseCampaignFromAddress(
+ value: string,
+): ParsedCampaignFromAddress | null {
+ const trimmed = value.trim();
+ if (!trimmed) return null;
+
+ const namedMatch = trimmed.match(/^(.+?)s*<([^<>s]+@[^<>s]+)>$/);
+ if (namedMatch) {
+ const displayName = namedMatch[1].trim();
+ const email = namedMatch[2].trim();
+
+ if (!displayName || !z.email().safeParse(email).success) {
+ return null;
+ }
+
+ return { displayName, email };
+ }
+
+ if (trimmed.includes("<") || trimmed.includes(">")) {
+ return null;
+ }
+
+ if (!z.email().safeParse(trimmed).success) {
+ return null;
+ }
+
+ return { displayName: null, email: trimmed };
+}
+
+export function formatCampaignFromAddress({
+ displayName,
+ email,
+}: ParsedCampaignFromAddress): string {
+ const normalizedEmail = email.toLowerCase();
+
+ if (displayName) {
+ return `${displayName.trim()} <${normalizedEmail}>`;
+ }
+
+ return normalizedEmail;
+}
+
+export function resolveCampaignFromAddress({
+ from,
+ programName,
+}: {
+ from: string;
+ programName: string;
+}): string {
+ const parsed = parseCampaignFromAddress(from);
+ if (!parsed) return from;
+
+ if (parsed.displayName) {
+ return formatCampaignFromAddress(parsed);
+ }
+
+ return `${programName} <${parsed.email.toLowerCase()}>`;
+}
diff --git a/apps/web/lib/zod/schemas/campaigns.ts b/apps/web/lib/zod/schemas/campaigns.ts
index c60ec31e74..b984dc9278 100644
--- a/apps/web/lib/zod/schemas/campaigns.ts
+++ b/apps/web/lib/zod/schemas/campaigns.ts
@@ -1,3 +1,7 @@
+import {
+ formatCampaignFromAddress,
+ parseCampaignFromAddress,
+} from "@/lib/email/parse-campaign-from-address";
import { CampaignStatus, CampaignType } from "@prisma/client";
import * as z from "zod/v4";
import { sendCampaignConditionSchema } from "../../api/workflows/send-campaign/schema";
@@ -12,6 +16,27 @@ export const EMAIL_TEMPLATE_VARIABLES = [
"PartnerLink",
] as const;
+export const CAMPAIGN_FROM_FORMAT_ERROR =
+ 'From must be an email or "Name <[email protected]>" format.';
+
+export const campaignFromSchema = z
+ .string()
+ .trim()
+ .min(1, CAMPAIGN_FROM_FORMAT_ERROR)
+ .transform((value, ctx) => {
+ const parsed = parseCampaignFromAddress(value);
+
+ if (!parsed) {
+ ctx.addIssue({
+ code: "custom",
+ message: CAMPAIGN_FROM_FORMAT_ERROR,
+ });
+ return z.NEVER;
+ }
+
+ return formatCampaignFromAddress(parsed);
+ });
+
export const CampaignSchema = z.object({
id: z.string(),
name: z.string(),
@@ -52,7 +77,7 @@ export const updateCampaignSchema = z
.trim()
.max(100, "Subject must be less than 100 characters."),
preview: z.string().nullish(),
- from: z.email().trim().toLowerCase(),
+ from: campaignFromSchema,
bodyJson: z.record(z.string(), z.any()),
triggerCondition: sendCampaignConditionSchema.nullish(),
groupIds: z.array(z.string()).nullable(),
diff --git a/apps/web/tests/misc/parse-campaign-from-address.test.ts b/apps/web/tests/misc/parse-campaign-from-address.test.ts
new file mode 100644
index 0000000000..b852e26f97
--- /dev/null
+++ b/apps/web/tests/misc/parse-campaign-from-address.test.ts
@@ -0,0 +1,102 @@
+import {
+ formatCampaignFromAddress,
+ parseCampaignFromAddress,
+ resolveCampaignFromAddress,
+} from "@/lib/email/parse-campaign-from-address";
+import {
+ CAMPAIGN_FROM_FORMAT_ERROR,
+ campaignFromSchema,
+} from "@/lib/zod/schemas/campaigns";
+import { describe, expect, it } from "vitest";
+
+describe("parseCampaignFromAddress", () => {
+ it.each([
+ [
+ "Alice from Acme <[email protected]>",
+ "Alice from Acme",
+ ],
+ [
+ " Bob from Acme <[email protected]> ",
+ "Bob from Acme",
+ ],
+ ])("parses %s", (input, displayName, email) => {
+ expect(parseCampaignFromAddress(input)).toEqual({ displayName, email });
+ });
+
+ it.each([
+ ["", "empty"],
+ ["Alice", "name only"],
+ ["Alice from Acme <[email protected]", "missing closing >"],
+ ["<[email protected]>", "empty display name"],
+ ["Alice <>", "empty email"],
+ ["Alice <not-an-email>", "invalid email in brackets"],
+ ["Name <[email protected]> extra", "trailing junk"],
+ ])("rejects invalid: %s — %s", (input) => {
+ expect(parseCampaignFromAddress(input)).toBeNull();
+ });
+});
+
+describe("formatCampaignFromAddress", () => {
+ it("formats a named address and lowercases the email", () => {
+ expect(
+ formatCampaignFromAddress({
+ displayName: "Alice from Acme",
+ email: "[email protected]",
+ }),
+ ).toBe("Alice from Acme <[email protected]>");
+ });
+
+ it("formats a bare email lowercased", () => {
+ expect(
+ formatCampaignFromAddress({
+ displayName: null,
+ email: "[email protected]",
+ }),
+ ).toBe("[email protected]");
+ });
+});
+
+describe("resolveCampaignFromAddress", () => {
+ it("wraps bare emails with the program name", () => {
+ expect(
+ resolveCampaignFromAddress({
+ programName: "Acme",
+ }),
+ ).toBe("Acme <[email protected]>");
+ });
+
+ it("passes through named addresses without using the program name", () => {
+ expect(
+ resolveCampaignFromAddress({
+ from: "Alice from Acme <[email protected]>",
+ programName: "Acme",
+ }),
+ ).toBe("Alice from Acme <[email protected]>");
+ });
+});
+
+describe("campaignFromSchema", () => {
+ it("accepts a bare email and lowercases it", () => {
+ expect(campaignFromSchema.parse("[email protected]")).toBe(
+ );
+ });
+
+ it("accepts Name <email> and preserves display name casing", () => {
+ expect(
+ campaignFromSchema.parse("Alice from Acme <[email protected]>"),
+ ).toBe("Alice from Acme <[email protected]>");
+ });
+
+ it("rejects invalid formats", () => {
+ const result = campaignFromSchema.safeParse("Alice");
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error.issues[0]?.message).toBe(CAMPAIGN_FROM_FORMAT_ERROR);
+ }
+ });
+});