Skip to content

Email for professionals and teams

Show the recipient address, with an optional full form

ssthormess8d08551b3c60
diff --git a/drizzle/migrations/0050_add_show_full_recipient_addresses.sql b/drizzle/migrations/0050_add_show_full_recipient_addresses.sql
new file mode 100644
index 0000000..2ac4f42
--- /dev/null
+++ b/drizzle/migrations/0050_add_show_full_recipient_addresses.sql
@@ -0,0 +1 @@
+ALTER TABLE `users` ADD `show_full_recipient_addresses` integer DEFAULT false NOT NULL;
diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.json
index 62e175c..7cbf8dc 100644
--- a/drizzle/migrations/meta/_journal.json
+++ b/drizzle/migrations/meta/_journal.json
@@ -295,6 +295,13 @@
"when": 1788850800013,
"tag": "0047_add_message_list_indexes",
"breakpoints": true
+ },
+ {
+ "idx": 42,
+ "version": "6",
+ "when": 1788850800014,
+ "tag": "0050_add_show_full_recipient_addresses",
+ "breakpoints": true
}
]
}
diff --git a/src/app/(dashboard)/inbox/[messageId]/page.tsx b/src/app/(dashboard)/inbox/[messageId]/page.tsx
index 50c6d68..519852b 100644
--- a/src/app/(dashboard)/inbox/[messageId]/page.tsx
+++ b/src/app/(dashboard)/inbox/[messageId]/page.tsx
@@ -22,7 +22,9 @@ import { ThreadMessageActions } from "@/components/messages/thread-message-actio
import { useMessageThread } from "@/components/messages/use-message-thread";
import { useLatestMessagesFirst } from "@/components/messages/use-latest-messages-first";
import { useMessageListVisibility } from "@/components/messages/message-list-visibility";
-import { getEmailAddress, getEmailDisplayName, splitEmailAddressList } from "@/lib/email/address";
+import { splitEmailAddressList } from "@/lib/email/address";
+import { RecipientList } from "@/components/messages/recipient-list";
+import { useShowFullRecipientAddresses } from "@/components/messages/use-show-full-recipient-addresses";
import type { MessageAttachment, MessageDetailResponse } from "./types";
import {
fetchMessageDetail,
@@ -50,6 +52,7 @@ export default function MessageDetailPage() {
useState<MessageAttachment | null>(null);
const [threadExpanded, setThreadExpanded] = useState(false);
const [latestMessagesFirst] = useLatestMessagesFirst();
+ const { enabled: showFullRecipientAddresses } = useShowFullRecipientAddresses();
const { visible: messageListVisible } = useMessageListVisibility();
usePageLoading(loading);
const thread = useMessageThread(messageId, data?.message?.threadId);
@@ -115,7 +118,7 @@ export default function MessageDetailPage() {
mailboxes.find((mailbox) => mailbox.id === message.mailboxId) ?? selectedMailbox;
const currentAccountName =
messageMailbox?.displayName ?? messageMailbox?.localPart;
- const { fromName, fromAddress, toName } = getMessageHeaderParties(
+ const { fromName, fromAddress } = getMessageHeaderParties(
message,
currentAccountName,
);
@@ -200,6 +203,7 @@ export default function MessageDetailPage() {
ownAddress={ownAddress}
ownAddresses={ownAddresses}
latestMessagesFirst={latestMessagesFirst}
+ showFullRecipientAddresses={showFullRecipientAddresses}
expandedAll={threadExpanded}
onExpandedAllChange={setThreadExpanded}
/>
@@ -234,24 +238,20 @@ export default function MessageDetailPage() {
</p>
<p className="text-xs text-neutral-500">
to{" "}
- {message.direction === "inbound" && toEntries.length <= 1 ? (
- toName
- ) : (
- <RecipientList
- entries={toEntries}
- mailboxId={message.mailboxId}
- firstName={message.direction === "outbound" ? toName : undefined}
- />
- )}
+ <RecipientList
+ entries={toEntries}
+ mailboxId={message.mailboxId}
+ style={showFullRecipientAddresses ? "full" : "address"}
+ />
</p>
{ccEntries.length > 0 && (
<p className="text-xs text-neutral-500">
- cc <RecipientList entries={ccEntries} mailboxId={message.mailboxId} />
+ cc <RecipientList entries={ccEntries} mailboxId={message.mailboxId} style={showFullRecipientAddresses ? "full" : "address"} />
</p>
)}
{bccEntries.length > 0 && (
<p className="text-xs text-neutral-500">
- bcc <RecipientList entries={bccEntries} mailboxId={message.mailboxId} />
+ bcc <RecipientList entries={bccEntries} mailboxId={message.mailboxId} style={showFullRecipientAddresses ? "full" : "address"} />
</p>
)}
</div>
@@ -342,6 +342,7 @@ export default function MessageDetailPage() {
ownAddress={ownAddress}
ownAddresses={ownAddresses}
latestMessagesFirst={latestMessagesFirst}
+ showFullRecipientAddresses={showFullRecipientAddresses}
expandedAll={threadExpanded}
onExpandedAllChange={setThreadExpanded}
/>
@@ -358,29 +359,3 @@ export default function MessageDetailPage() {
);
}
-function RecipientList({
- entries,
- mailboxId,
- firstName,
-}: {
- entries: string[];
- mailboxId: string | null;
- /** A contact name already resolved for the first entry, when the caller has one. */
- firstName?: string;
-}) {
- if (entries.length === 0) return <>—</>;
- return (
- <>
- {entries.map((entry, index) => (
- <span key={entry} title={getEmailAddress(entry)}>
- {index > 0 && ", "}
- <ContactDetailsTrigger
- mailboxId={mailboxId}
- address={entry}
- name={index === 0 && firstName ? firstName : getEmailDisplayName(entry)}
- />
- </span>
- ))}
- </>
- );
-}
diff --git a/src/app/(dashboard)/inbox/[messageId]/utils.ts b/src/app/(dashboard)/inbox/[messageId]/utils.ts
index dd485b5..084d861 100644
--- a/src/app/(dashboard)/inbox/[messageId]/utils.ts
+++ b/src/app/(dashboard)/inbox/[messageId]/utils.ts
@@ -1,6 +1,7 @@
import { authFetch } from "@/lib/auth/client";
import { fetchCachedMessageDetail, getCachedMessageDetail } from "@/lib/messages/detail-cache";
import { getEmailAddress, getEmailAddressList, normalizeEmailAddress } from "@/lib/email/address";
+import { formatRecipientAddressList } from "@/lib/email/recipient-display";
import { getDisplayNameForAddress } from "@/lib/contacts/utils";
import { htmlToReadableText, splitRepliedEmailContent } from "@/lib/email/reply-content-utils";
import { splitQuotedHtml } from "@/components/compose/rich-text-utils";
@@ -28,7 +29,7 @@ export function getMessageHeaderParties(message: Message, currentAccountName?: s
fromAddress: getEmailAddress(message.fromAddr),
toName:
message.direction === "inbound"
- ? "me"
+ ? formatRecipientAddressList(message.toAddr, "address") || "—"
: getDisplayNameForAddress(message.toAddr, message.toContactName),
};
}
diff --git a/src/app/(settings)/settings/inbox/page.tsx b/src/app/(settings)/settings/inbox/page.tsx
index fc7692f..f9dd33e 100644
--- a/src/app/(settings)/settings/inbox/page.tsx
+++ b/src/app/(settings)/settings/inbox/page.tsx
@@ -1,5 +1,6 @@
import { AppearanceSettings } from "@/components/settings/appearance-settings";
import { InboxThreadingSettings } from "@/components/settings/inbox-threading-settings";
+import { RecipientAddressSettings } from "@/components/settings/recipient-address-settings";
import { InboxReadingLayoutSettings } from "@/components/settings/inbox-reading-layout-settings";
import { InboxShortcutsSettings } from "@/components/settings/inbox-shortcuts-settings";
import { MailboxAutoReplyForm } from "@/components/settings/mailbox-auto-reply-form";
@@ -36,6 +37,13 @@ export default function SettingsInboxPage() {
</div>
<InboxThreadingSettings />
</div>
+ <div className="py-6 first:pt-0 last:pb-0">
+ <div className="mb-4">
+ <h3 className="text-base font-semibold text-neutral-900">Addresses</h3>
+ <p className="mt-1 text-sm text-neutral-500">Choose how recipient addresses appear when you read mail.</p>
+ </div>
+ <RecipientAddressSettings />
+ </div>
<div className="py-6 first:pt-0 last:pb-0">
<div className="mb-4">
<h3 className="text-base font-semibold text-neutral-900">Shortcuts</h3>
diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.ts
index ffff900..27c3534 100644
--- a/src/app/api/auth/me/route.ts
+++ b/src/app/api/auth/me/route.ts
@@ -36,6 +36,7 @@ export async function GET(request: Request) {
canManageMailboxes: user.canManageMailboxes,
keyboardShortcutsEnabled: user.keyboardShortcutsEnabled,
spamProtectionEnabled: user.spamProtectionEnabled,
+ showFullRecipientAddresses: user.showFullRecipientAddresses,
hasAvatar: !!user.avatarKey,
mfaEnabled: user.totpEnabled,
},
diff --git a/src/app/api/settings/recipient-addresses/route.ts b/src/app/api/settings/recipient-addresses/route.ts
new file mode 100644
index 0000000..d406704
--- /dev/null
+++ b/src/app/api/settings/recipient-addresses/route.ts
@@ -0,0 +1,36 @@
+import { eq } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { ZodError } from "zod";
+import { getDb } from "@/db";
+import { users } from "@/db/schema";
+import { requireSessionUser } from "@/lib/api/auth";
+import { getEnv } from "@/lib/cloudflare";
+import type { UpdateRecipientAddressSettingsInput } from "./types";
+import { parseUpdateRecipientAddressSettingsRequest } from "./utils";
+
+export async function GET(request: Request) {
+ const env = getEnv();
+ const auth = await requireSessionUser(env, request);
+ if (auth.error) return auth.error;
+ return NextResponse.json({ enabled: auth.user.showFullRecipientAddresses });
+}
+
+export async function PATCH(request: Request) {
+ const env = getEnv();
+ const auth = await requireSessionUser(env, request);
+ if (auth.error) return auth.error;
+
+ let input: UpdateRecipientAddressSettingsInput;
+ try {
+ input = await parseUpdateRecipientAddressSettingsRequest(request);
+ } catch (error) {
+ return NextResponse.json({ error: error instanceof ZodError ? error.flatten() : "Invalid request" }, { status: 400 });
+ }
+
+ await getDb(env)
+ .update(users)
+ .set({ showFullRecipientAddresses: input.enabled })
+ .where(eq(users.id, auth.user.id));
+
+ return NextResponse.json({ enabled: input.enabled });
+}
diff --git a/src/app/api/settings/recipient-addresses/types.d.ts b/src/app/api/settings/recipient-addresses/types.d.ts
new file mode 100644
index 0000000..3a7cdba
--- /dev/null
+++ b/src/app/api/settings/recipient-addresses/types.d.ts
@@ -0,0 +1,4 @@
+import type { updateRecipientAddressSettingsSchema } from "@/lib/validators";
+import type { z } from "zod";
+
+export type UpdateRecipientAddressSettingsInput = z.infer<typeof updateRecipientAddressSettingsSchema>;
diff --git a/src/app/api/settings/recipient-addresses/utils.ts b/src/app/api/settings/recipient-addresses/utils.ts
new file mode 100644
index 0000000..8490a63
--- /dev/null
+++ b/src/app/api/settings/recipient-addresses/utils.ts
@@ -0,0 +1,8 @@
+import { updateRecipientAddressSettingsSchema } from "@/lib/validators";
+import type { UpdateRecipientAddressSettingsInput } from "./types";
+
+export async function parseUpdateRecipientAddressSettingsRequest(
+ request: Request,
+): Promise<UpdateRecipientAddressSettingsInput> {
+ return updateRecipientAddressSettingsSchema.parse(await request.json());
+}
diff --git a/src/components/contacts/contact-details-types.d.ts b/src/components/contacts/contact-details-types.d.ts
index ac32863..dac85a1 100644
--- a/src/components/contacts/contact-details-types.d.ts
+++ b/src/components/contacts/contact-details-types.d.ts
@@ -15,6 +15,9 @@ export type ContactDetailsResponse = {
export type ContactDetailsTriggerProps = {
mailboxId: string | null;
address: string;
+ /** Contact name. Not the formatted Name <mailbox> label. */
name: string;
+ /** Visible text. Falls back to name. */
+ label?: string;
className?: string;
};
diff --git a/src/components/contacts/contact-details.tsx b/src/components/contacts/contact-details.tsx
index 1ef8c2d..b9c8cee 100644
--- a/src/components/contacts/contact-details.tsx
+++ b/src/components/contacts/contact-details.tsx
@@ -23,30 +23,35 @@ export function ContactDetailsTrigger({
mailboxId,
address,
name,
+ label,
className,
}: ContactDetailsTriggerProps) {
const [open, setOpen] = useState(false);
- const [shownName, setShownName] = useState(name);
+ const visibleLabel = label ?? name;
+ const [renamed, setRenamed] = useState<{ from: string; value: string } | null>(null);
+ const shownName = renamed?.from === visibleLabel ? renamed.value : visibleLabel;
const [contact, setContact] = useState<ContactDetailsRecord | null>(null);
const [displayName, setDisplayName] = useState(name);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
- useEffect(() => {
- setShownName(name);
- }, [name]);
+ function handleOpenChange(next: boolean) {
+ if (next) {
+ setLoading(true);
+ setError(null);
+ }
+ setOpen(next);
+ }
useEffect(() => {
if (!open || !mailboxId) return;
let cancelled = false;
- setLoading(true);
- setError(null);
fetchContactDetails(mailboxId, address)
.then((nextContact) => {
if (cancelled) return;
setContact(nextContact);
- setDisplayName(nextContact.displayName ?? shownName);
+ setDisplayName(nextContact.displayName ?? name);
})
.catch((loadError) => {
if (!cancelled) setError(loadError instanceof Error ? loadError.message : "Unable to load contact");
@@ -57,7 +62,7 @@ export function ContactDetailsTrigger({
return () => {
cancelled = true;
};
- }, [address, mailboxId, open, shownName]);
+ }, [address, mailboxId, name, open]);
async function saveContact() {
if (!mailboxId || !displayName.trim()) return;
@@ -67,7 +72,7 @@ export function ContactDetailsTrigger({
const updated = await updateContactName(mailboxId, address, displayName);
const nextName = updated.displayName ?? displayName.trim();
setContact(updated);
- setShownName(nextName);
+ if (!label) setRenamed({ from: visibleLabel, value: nextName });
setOpen(false);
window.dispatchEvent(new CustomEvent("mailflare:contact-changed", {
detail: { email: updated.email, displayName: nextName },
@@ -85,12 +90,12 @@ export function ContactDetailsTrigger({
<>
<button
type="button"
- onClick={() => setOpen(true)}
+ onClick={() => handleOpenChange(true)}
className={`${className ?? ""} rounded-sm text-left hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-200`}
>
{shownName}
</button>
- <Dialog open={open} onOpenChange={setOpen}>
+ <Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Contact details</DialogTitle>
@@ -101,7 +106,7 @@ export function ContactDetailsTrigger({
<ContactAvatarForm
mailboxId={mailboxId}
address={address}
- name={shownName}
+ name={displayName}
hasAvatar={contact?.hasAvatar ?? false}
onAvatarChange={(hasAvatar) => setContact((current) => current ? { ...current, hasAvatar } : current)}
/>
diff --git a/src/components/messages/conversation-thread-types.d.ts b/src/components/messages/conversation-thread-types.d.ts
index 6e12459..25ca870 100644
--- a/src/components/messages/conversation-thread-types.d.ts
+++ b/src/components/messages/conversation-thread-types.d.ts
@@ -13,6 +13,7 @@ export type ConversationThreadProps = {
latestMessagesFirst: boolean;
expandedAll: boolean;
onExpandedAllChange: (expanded: boolean) => void;
+ showFullRecipientAddresses?: boolean;
};
export type ConversationMessageCardProps = {
@@ -22,6 +23,7 @@ export type ConversationMessageCardProps = {
ownAddress?: string | null;
ownAddresses?: string[];
defaultExpanded?: boolean;
+ showFullRecipientAddresses?: boolean;
};
export type UseMessageThreadResult = {
diff --git a/src/components/messages/conversation-thread-utils.ts b/src/components/messages/conversation-thread-utils.ts
index c5b111a..dd3e2d8 100644
--- a/src/components/messages/conversation-thread-utils.ts
+++ b/src/components/messages/conversation-thread-utils.ts
@@ -1,4 +1,5 @@
import { getEmailAddress, getEmailDisplayName, splitEmailAddressList } from "@/lib/email/address";
+import { formatRecipientAddress, type RecipientAddressStyle } from "@/lib/email/recipient-display";
import type { ThreadMessage } from "@/hooks/types";
/** Messages on one side of the current one, in chronological order. */
@@ -26,10 +27,10 @@ export function getConversationSenderEmail(message: ThreadMessage): string {
}
-/** "to Maya, Sam" style summary for a collapsed card. */
-export function getConversationRecipients(message: ThreadMessage): string {
+/** Recipient summary for a thread card. Same address or full form as the open message. */
+export function getConversationRecipients(message: ThreadMessage, style: RecipientAddressStyle = "address"): string {
const names = [...splitEmailAddressList(message.toAddr), ...splitEmailAddressList(message.ccAddr)].map(
- (entry) => getEmailDisplayName(entry),
+ (entry) => formatRecipientAddress(entry, style),
);
if (names.length === 0) return "";
if (names.length <= 3) return names.join(", ");
diff --git a/src/components/messages/conversation-thread.tsx b/src/components/messages/conversation-thread.tsx
index cab63c4..19cc67c 100644
--- a/src/components/messages/conversation-thread.tsx
+++ b/src/components/messages/conversation-thread.tsx
@@ -38,6 +38,7 @@ export function ConversationThread({
latestMessagesFirst,
expandedAll,
onExpandedAllChange,
+ showFullRecipientAddresses = false,
}: ConversationThreadProps) {
const slice = partitionThread(messages, currentMessageId, position, latestMessagesFirst);
if (slice.length === 0) return null;
@@ -60,6 +61,7 @@ export function ConversationThread({
currentAccountName={currentAccountName}
ownAddress={ownAddress}
ownAddresses={ownAddresses}
+ showFullRecipientAddresses={showFullRecipientAddresses}
/>
</li>
{collapsed ? (
@@ -86,6 +88,7 @@ export function ConversationThread({
currentAccountName={currentAccountName}
ownAddress={ownAddress}
ownAddresses={ownAddresses}
+ showFullRecipientAddresses={showFullRecipientAddresses}
/>
</li>
))
@@ -98,6 +101,7 @@ export function ConversationThread({
currentAccountName={currentAccountName}
ownAddress={ownAddress}
ownAddresses={ownAddresses}
+ showFullRecipientAddresses={showFullRecipientAddresses}
/>
</li>
)}
@@ -113,13 +117,14 @@ export function ConversationMessageCard({
ownAddress,
ownAddresses,
defaultExpanded = false,
+ showFullRecipientAddresses = false,
}: ConversationMessageCardProps) {
const [locallyExpanded, setLocallyExpanded] = useState(defaultExpanded);
const [locallyRead, setLocallyRead] = useState(message.read);
const expanded = locallyExpanded;
const sender = getConversationSender(message, currentAccountName);
const senderEmail = getConversationSenderEmail(message);
- const recipients = getConversationRecipients(message);
+ const recipients = getConversationRecipients(message, showFullRecipientAddresses ? "full" : "address");
// const href = `${getMessageBackHref(message.direction, message.status)}/${message.id}`;
const outbound = message.direction === "outbound";
const attachments = message.attachments.filter((attachment) => attachment.disposition === "attachment");
diff --git a/src/components/messages/recipient-list.tsx b/src/components/messages/recipient-list.tsx
new file mode 100644
index 0000000..ce91ae0
--- /dev/null
+++ b/src/components/messages/recipient-list.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import { ContactDetailsTrigger } from "@/components/contacts/contact-details";
+import { getEmailAddress } from "@/lib/email/address";
+import { formatRecipientAddress, recipientContactName, type RecipientAddressStyle } from "@/lib/email/recipient-display";
+
+export function RecipientList({
+ entries,
+ mailboxId,
+ style,
+}: {
+ entries: string[];
+ mailboxId: string | null;
+ style: RecipientAddressStyle;
+}) {
+ if (entries.length === 0) return <>—</>;
+ return (
+ <>
+ {entries.map((entry, index) => (
+ <span key={`${entry}-${index}`} title={getEmailAddress(entry)}>
+ {index > 0 && ", "}
+ <ContactDetailsTrigger
+ mailboxId={mailboxId}
+ address={entry}
+ name={recipientContactName(entry)}
+ label={formatRecipientAddress(entry, style)}
+ />
+ </span>
+ ))}
+ </>
+ );
+}
diff --git a/src/components/messages/use-show-full-recipient-addresses-utils.ts b/src/components/messages/use-show-full-recipient-addresses-utils.ts
new file mode 100644
index 0000000..d3340b4
--- /dev/null
+++ b/src/components/messages/use-show-full-recipient-addresses-utils.ts
@@ -0,0 +1,28 @@
+import { authFetch } from "@/lib/auth/client";
+
+type RecipientAddressSettingsResponse = {
+ enabled?: boolean;
+ error?: string;
+};
+
+async function readEnabled(response: Response, fallback: string): Promise<boolean> {
+ const data = (await response.json()) as RecipientAddressSettingsResponse;
+ if (!response.ok || typeof data.enabled !== "boolean") {
+ throw new Error(typeof data.error === "string" ? data.error : fallback);
+ }
+ return data.enabled;
+}
+
+export async function loadShowFullRecipientAddresses(): Promise<boolean> {
+ const response = await authFetch("/api/settings/recipient-addresses");
+ return readEnabled(response, "Failed to load recipient address settings");
+}
+
+export async function updateShowFullRecipientAddresses(enabled: boolean): Promise<boolean> {
+ const response = await authFetch("/api/settings/recipient-addresses", {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ enabled }),
+ });
+ return readEnabled(response, "Failed to update recipient address settings");
+}
diff --git a/src/components/messages/use-show-full-recipient-addresses.ts b/src/components/messages/use-show-full-recipient-addresses.ts
new file mode 100644
index 0000000..5f14d4d
--- /dev/null
+++ b/src/components/messages/use-show-full-recipient-addresses.ts
@@ -0,0 +1,45 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { loadShowFullRecipientAddresses, updateShowFullRecipientAddresses } from "./use-show-full-recipient-addresses-utils";
+
+/** The signed-in user's choice for To, Cc, and Bcc. Default is the mailbox only. */
+export function useShowFullRecipientAddresses() {
+ const [enabled, setEnabledState] = useState(false);
+ const [isLoading, setIsLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ loadShowFullRecipientAddresses()
+ .then((stored) => {
+ if (!cancelled) setEnabledState(stored);
+ })
+ .catch((loadError) => {
+ if (cancelled) return;
+ setError(loadError instanceof Error ? loadError.message : "Failed to load recipient address settings");
+ })
+ .finally(() => {
+ if (!cancelled) setIsLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const setEnabled = useCallback(async (next: boolean) => {
+ const previous = enabled;
+ setEnabledState(next);
+ setError(null);
+ try {
+ setEnabledState(await updateShowFullRecipientAddresses(next));
+ } catch (updateError) {
+ setEnabledState(previous);
+ const message = updateError instanceof Error ? updateError.message : "Failed to update recipient address settings";
+ setError(message);
+ throw new Error(message);
+ }
+ }, [enabled]);
+
+ return { enabled, error, isLoading, setEnabled };
+}
diff --git a/src/components/settings/recipient-address-settings.tsx b/src/components/settings/recipient-address-settings.tsx
new file mode 100644
index 0000000..f7bb482
--- /dev/null
+++ b/src/components/settings/recipient-address-settings.tsx
@@ -0,0 +1,37 @@
+"use client";
+
+import { useState } from "react";
+import { useShowFullRecipientAddresses } from "@/components/messages/use-show-full-recipient-addresses";
+import { Switch } from "@/components/ui/switch";
+
+export function RecipientAddressSettings() {
+ const { enabled, error, isLoading, setEnabled } = useShowFullRecipientAddresses();
+ const [saving, setSaving] = useState(false);
+ const [saveError, setSaveError] = useState<string | null>(null);
+
+ return (
+ <div>
+ <label className="flex items-start gap-3 rounded-xl bg-neutral-50 p-4">
+ <span className="flex-1">
+ <span className="block text-sm font-medium text-neutral-900">Show full recipient addresses</span>
+ <span className="mt-1 block text-sm text-neutral-500">
+ On To, Cc, and Bcc, show Name &lt;[email protected]&gt; when the message includes a name. Off shows only the email address. This follows your sign-in, on every mailbox.
+ </span>
+ </span>
+ <Switch
+ checked={enabled}
+ disabled={isLoading || saving}
+ onCheckedChange={(next) => {
+ setSaving(true);
+ setSaveError(null);
+ void setEnabled(next)
+ .catch((updateError) => setSaveError(updateError instanceof Error ? updateError.message : "Failed to update recipient address settings"))
+ .finally(() => setSaving(false));
+ }}
+ aria-label="Show full recipient addresses"
+ />
+ </label>
+ {(saveError || error) && <p className="mt-2 px-4 text-sm text-red-600">{saveError || error}</p>}
+ </div>
+ );
+}
diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts
index 0f46f94..5f7473e 100644
--- a/src/db/schema/index.ts
+++ b/src/db/schema/index.ts
@@ -17,6 +17,8 @@ export const users = sqliteTable("users", {
canManageMailboxes: integer("can_manage_mailboxes", { mode: "boolean" }).notNull().default(false),
keyboardShortcutsEnabled: integer("keyboard_shortcuts_enabled", { mode: "boolean" }).notNull().default(true),
spamProtectionEnabled: integer("spam_protection_enabled", { mode: "boolean" }).notNull().default(true),
+ // Off shows the mailbox only. On shows Name <mailbox> on To, Cc, and Bcc.
+ showFullRecipientAddresses: integer("show_full_recipient_addresses", { mode: "boolean" }).notNull().default(false),
// TOTP second factor. The secret is written at enrolment and only counts
// once the user has proven a code from their authenticator.
totpSecret: text("totp_secret"),
diff --git a/src/lib/auth/types.d.ts b/src/lib/auth/types.d.ts
index 052628a..663c798 100644
--- a/src/lib/auth/types.d.ts
+++ b/src/lib/auth/types.d.ts
@@ -13,6 +13,7 @@ export type SessionUser = {
canManageMailboxes: boolean;
keyboardShortcutsEnabled: boolean;
spamProtectionEnabled: boolean;
+ showFullRecipientAddresses: boolean;
createdByUserId: string | null;
createdAt: Date;
};
diff --git a/src/lib/email/recipient-display.ts b/src/lib/email/recipient-display.ts
new file mode 100644
index 0000000..df7b9b9
--- /dev/null
+++ b/src/lib/email/recipient-display.ts
@@ -0,0 +1,24 @@
+import { getEmailAddress, parseEmailAddressParts, splitEmailAddressList } from "@/lib/email/address";
+
+/** address: mailbox only. full: Name <mailbox> when the header has a display name. */
+export type RecipientAddressStyle = "address" | "full";
+
+export function formatRecipientAddress(entry: string, style: RecipientAddressStyle): string {
+ const address = getEmailAddress(entry).trim();
+ if (!address) return entry.trim();
+ if (style !== "full") return address;
+ const name = parseEmailAddressParts(entry).name?.trim();
+ if (!name) return address;
+ return `${name} <${address}>`;
+}
+
+export function formatRecipientAddressList(value: string | null | undefined, style: RecipientAddressStyle): string {
+ return splitEmailAddressList(value)
+ .map((entry) => formatRecipientAddress(entry, style))
+ .join(", ");
+}
+
+/** Name to store on a contact. Never the formatted Name <mailbox> label. */
+export function recipientContactName(entry: string): string {
+ return parseEmailAddressParts(entry).name?.trim() || getEmailAddress(entry).trim() || entry.trim();
+}
diff --git a/src/lib/validators.ts b/src/lib/validators.ts
index 4dccafe..5a0d0b3 100644
--- a/src/lib/validators.ts
+++ b/src/lib/validators.ts
@@ -229,6 +229,10 @@ export const updateSpamSettingsSchema = z.object({
enabled: z.boolean(),
});
+export const updateRecipientAddressSettingsSchema = z.object({
+ enabled: z.boolean(),
+});
+
export const changePasswordSchema = z.object({
currentPassword: z.string().min(1),
newPassword: z.string().min(8).max(128),
diff --git a/tests/recipient-display.test.mjs b/tests/recipient-display.test.mjs
new file mode 100644
index 0000000..33d706a
--- /dev/null
+++ b/tests/recipient-display.test.mjs
@@ -0,0 +1,111 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test, { after } from "node:test";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { build } from "esbuild";
+import Database from "better-sqlite3";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const outDir = mkdtempSync(join(tmpdir(), "mailflare-recipient-display-"));
+after(() => rmSync(outDir, { recursive: true, force: true }));
+
+async function bundle(entry, outfile) {
+ await build({
+ entryPoints: [join(root, entry)],
+ outfile: join(outDir, outfile),
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ target: "node22",
+ logLevel: "silent",
+ alias: { "@": join(root, "src") },
+ external: ["react", "react-dom", "next", "next/*"],
+ });
+ return import(pathToFileURL(join(outDir, outfile)).href);
+}
+
+const display = await bundle("src/lib/email/recipient-display.ts", "display.mjs");
+const thread = await bundle("src/components/messages/conversation-thread-utils.ts", "thread.mjs");
+const parties = await bundle("src/app/(dashboard)/inbox/[messageId]/utils.ts", "parties.mjs");
+const validators = await bundle("src/lib/validators.ts", "validators.mjs");
+
+test("address style drops the display name", () => {
+ assert.equal(display.formatRecipientAddress("Catch All <[email protected]>", "address"), "[email protected]");
+ assert.equal(display.formatRecipientAddress('"Chen, Maya" <[email protected]>', "address"), "[email protected]");
+ assert.equal(display.formatRecipientAddress("[email protected]", "address"), "[email protected]");
+});
+
+test("full style keeps Name <mailbox> and leaves a bare address alone", () => {
+ assert.equal(display.formatRecipientAddress("Redacción <[email protected]>", "full"), "Redacción <[email protected]>");
+ assert.equal(display.formatRecipientAddress('"Chen, Maya" <[email protected]>', "full"), "Chen, Maya <[email protected]>");
+ assert.equal(display.formatRecipientAddress("[email protected]", "full"), "[email protected]");
+ assert.equal(
+ display.formatRecipientAddressList("Ada <[email protected]>, [email protected]", "full"),
+ );
+});
+
+test("contact name is never the formatted label", () => {
+ assert.equal(display.recipientContactName('"Chen, Maya" <[email protected]>'), "Chen, Maya");
+ assert.equal(display.recipientContactName("[email protected]"), "[email protected]");
+});
+
+test("thread cards follow the same style and still collapse a long list", () => {
+ const message = {
+ ccAddr: "",
+ };
+ assert.equal(thread.getConversationRecipients(message, "address"), "[email protected], [email protected], [email protected], +1");
+ assert.equal(
+ thread.getConversationRecipients(message, "full"),
+ );
+});
+
+test("inbound To is the address, not me", () => {
+ const header = parties.getMessageHeaderParties({
+ direction: "inbound",
+ fromAddr: "Ada Lovelace <[email protected]>",
+ toAddr: "Catch All <[email protected]>",
+ });
+ assert.equal(header.toName, "[email protected]");
+ assert.equal(header.toName.includes("me"), false);
+
+ const several = parties.getMessageHeaderParties({
+ direction: "inbound",
+ fromAddr: "[email protected]",
+ });
+ assert.equal(several.toName, "[email protected], [email protected]");
+});
+
+test("outbound To still prefers the contact name", () => {
+ const header = parties.getMessageHeaderParties({
+ direction: "outbound",
+ fromAddr: "[email protected]",
+ toAddr: "Ada <[email protected]>",
+ toContactName: "Ada Lovelace",
+ });
+ assert.equal(header.toName, "Ada Lovelace");
+});
+
+test("the setting accepts only a boolean", () => {
+ assert.equal(validators.updateRecipientAddressSettingsSchema.parse({ enabled: true }).enabled, true);
+ assert.equal(validators.updateRecipientAddressSettingsSchema.parse({ enabled: false }).enabled, false);
+ assert.throws(() => validators.updateRecipientAddressSettingsSchema.parse({ enabled: "yes" }));
+});
+
+test("migration adds the user column off by default and the journal lists it", () => {
+ const db = new Database(":memory:");
+ db.exec("CREATE TABLE users (id text primary key)");
+ db.exec(readFileSync(join(root, "drizzle/migrations/0050_add_show_full_recipient_addresses.sql"), "utf8"));
+ db.exec("INSERT INTO users (id) VALUES ('u')");
+ assert.equal(db.prepare("SELECT show_full_recipient_addresses AS value FROM users").get().value, 0);
+
+ const journal = JSON.parse(readFileSync(join(root, "drizzle/migrations/meta/_journal.json"), "utf8"));
+ assert.equal(journal.entries.at(-1).tag, "0050_add_show_full_recipient_addresses");
+ assert.equal(journal.entries.at(-1).idx, 42);
+});