Skip to content

Email for professionals and teams

merge forwarding section with rules settings #106

Hieu Nguyen (Jack)fa7f8156438e
diff --git a/src/app/api/routing-rules/[id]/route.ts b/src/app/api/routing-rules/[id]/route.ts
index 32aa979..0dbc02c 100644
--- a/src/app/api/routing-rules/[id]/route.ts
+++ b/src/app/api/routing-rules/[id]/route.ts
@@ -1,11 +1,12 @@
-import { and, eq } from "drizzle-orm";
+import { eq } from "drizzle-orm";
import { NextResponse } from "next/server";
import { getDb } from "@/db";
-import { folders, routingRules } from "@/db/schema";
+import { routingRules } from "@/db/schema";
import { requireUser } from "@/lib/auth/cookies";
import { getEnv } from "@/lib/cloudflare";
import { getMailboxAccessLevel } from "@/lib/mailboxes/access";
import { routingRuleSchema } from "@/lib/validators";
+import { resolveRuleTarget } from "../utils";
import type { RoutingRuleRouteParams } from "./types";
export async function PATCH(request: Request, { params }: RoutingRuleRouteParams) {
@@ -27,21 +28,9 @@ export async function PATCH(request: Request, { params }: RoutingRuleRouteParams
return NextResponse.json({ error: "Rule not found" }, { status: 404 });
}
- const destination = parsed.data.destination ?? (parsed.data.folderId ? `folder:${parsed.data.folderId}` : "");
- const systemAction = destination === "spam" || destination === "trash" ? destination : null;
- const folderId = destination.startsWith("folder:") ? destination.slice("folder:".length) : null;
- if (!systemAction && !folderId) {
- return NextResponse.json({ error: "Destination is required" }, { status: 400 });
- }
- if (folderId) {
- const [folder] = await db
- .select()
- .from(folders)
- .where(and(eq(folders.id, folderId), eq(folders.mailboxId, rule.mailboxId)))
- .limit(1);
- if (!folder) {
- return NextResponse.json({ error: "Folder not found" }, { status: 404 });
- }
+ const target = await resolveRuleTarget(db, rule.mailboxId, parsed.data);
+ if ("error" in target) {
+ return NextResponse.json({ error: target.error }, { status: target.status });
}
await db
@@ -51,9 +40,10 @@ export async function PATCH(request: Request, { params }: RoutingRuleRouteParams
matchField: parsed.data.matchField,
matchOperator: parsed.data.matchOperator,
matchValue: parsed.data.matchValue.trim(),
- action: systemAction ?? "store",
- folderId,
- forwardTo: null,
+ action: target.action,
+ folderId: target.folderId,
+ forwardTo: target.forwardTo,
+ keepCopy: target.keepCopy,
priority: parsed.data.priority,
})
.where(eq(routingRules.id, id));
diff --git a/src/app/api/routing-rules/route.ts b/src/app/api/routing-rules/route.ts
index 34dda66..4495d43 100644
--- a/src/app/api/routing-rules/route.ts
+++ b/src/app/api/routing-rules/route.ts
@@ -2,11 +2,12 @@ import { NextResponse } from "next/server";
import { and, eq } from "drizzle-orm";
import { getEnv } from "@/lib/cloudflare";
import { getDb } from "@/db";
-import { folders, routingRules } from "@/db/schema";
+import { routingRules } from "@/db/schema";
import { requireUser } from "@/lib/auth/cookies";
import { newId } from "@/lib/ids";
import { getMailboxAccessLevel } from "@/lib/mailboxes/access";
import { routingRuleSchema } from "@/lib/validators";
+import { resolveRuleTarget } from "./utils";
export async function GET(request: Request) {
const env = getEnv();
@@ -45,23 +46,9 @@ export async function POST(request: Request) {
}
const mailbox = access.mailbox;
- const destination = parsed.data.destination ?? (parsed.data.folderId ? `folder:${parsed.data.folderId}` : "");
- const systemAction = destination === "spam" || destination === "trash" ? destination : null;
- const folderId = destination.startsWith("folder:") ? destination.slice("folder:".length) : null;
-
- if (!systemAction && !folderId) {
- return NextResponse.json({ error: "Destination is required" }, { status: 400 });
- }
-
- if (folderId) {
- const [folder] = await db
- .select()
- .from(folders)
- .where(and(eq(folders.id, folderId), eq(folders.mailboxId, mailbox.id)))
- .limit(1);
- if (!folder) {
- return NextResponse.json({ error: "Folder not found" }, { status: 404 });
- }
+ const target = await resolveRuleTarget(db, mailbox.id, parsed.data);
+ if ("error" in target) {
+ return NextResponse.json({ error: target.error }, { status: target.status });
}
const id = newId("rule");
@@ -74,10 +61,11 @@ export async function POST(request: Request) {
matchField: parsed.data.matchField,
matchOperator: parsed.data.matchOperator,
matchValue: parsed.data.matchValue.trim(),
- action: systemAction ?? "store",
+ action: target.action,
mailboxId: mailbox.id,
- folderId,
- forwardTo: null,
+ folderId: target.folderId,
+ forwardTo: target.forwardTo,
+ keepCopy: target.keepCopy,
priority: parsed.data.priority,
});
diff --git a/src/app/api/routing-rules/types.d.ts b/src/app/api/routing-rules/types.d.ts
new file mode 100644
index 0000000..42f4963
--- /dev/null
+++ b/src/app/api/routing-rules/types.d.ts
@@ -0,0 +1,6 @@
+export type RuleTarget = {
+ action: "store" | "forward" | "spam" | "trash";
+ folderId: string | null;
+ forwardTo: string | null;
+ keepCopy: boolean;
+};
diff --git a/src/app/api/routing-rules/utils.ts b/src/app/api/routing-rules/utils.ts
new file mode 100644
index 0000000..1511454
--- /dev/null
+++ b/src/app/api/routing-rules/utils.ts
@@ -0,0 +1,49 @@
+import { and, eq } from "drizzle-orm";
+import type { AppDatabase } from "@/db";
+import { folders } from "@/db/schema";
+import type { routingRuleSchema } from "@/lib/validators";
+import type { z } from "zod";
+import type { RuleTarget } from "./types";
+
+/**
+ * Turns a mailbox rule's `destination` into the columns that store it. Returns an
+ * `error` and `status` instead when the destination is missing or not usable.
+ */
+export async function resolveRuleTarget(
+ db: AppDatabase,
+ mailboxId: string,
+ input: z.infer<typeof routingRuleSchema>,
+): Promise<RuleTarget | { error: string; status: number }> {
+ const destination = input.destination ?? (input.folderId ? `folder:${input.folderId}` : "");
+
+ if (destination === "forward") {
+ // Forwards are actioned while the message is still being received, before its body is
+ // available, so a rule that matches on content can never fire.
+ if (input.matchField === "content") {
+ return { error: "Forwarding rules cannot match on message content", status: 400 };
+ }
+ if (!input.forwardTo) return { error: "A forwarding address is required", status: 400 };
+ return {
+ action: "forward",
+ folderId: null,
+ forwardTo: input.forwardTo,
+ keepCopy: input.keepCopy ?? false,
+ };
+ }
+
+ if (destination === "spam" || destination === "trash") {
+ return { action: destination, folderId: null, forwardTo: null, keepCopy: false };
+ }
+
+ const folderId = destination.startsWith("folder:") ? destination.slice("folder:".length) : null;
+ if (!folderId) return { error: "Destination is required", status: 400 };
+
+ const [folder] = await db
+ .select({ id: folders.id })
+ .from(folders)
+ .where(and(eq(folders.id, folderId), eq(folders.mailboxId, mailboxId)))
+ .limit(1);
+ if (!folder) return { error: "Folder not found", status: 404 };
+
+ return { action: "store", folderId, forwardTo: null, keepCopy: false };
+}
diff --git a/src/components/loading-transition.tsx b/src/components/loading-transition.tsx
index 4dd78a2..2d8817a 100644
--- a/src/components/loading-transition.tsx
+++ b/src/components/loading-transition.tsx
@@ -104,7 +104,7 @@ export function LoadingTransition({ children, ready }: LoadingTransitionProps) {
<div aria-hidden="true" className="flex w-64 flex-col items-center gap-6">
<img
src={iconUrl}
- onError={() => setIconUrl("/icon-96.png")}
+ onError={() => setIconUrl("/icon-192.png")}
alt=""
className="h-20 w-20 rounded-2xl object-contain"
/>
diff --git a/src/components/settings/account-settings.tsx b/src/components/settings/account-settings.tsx
index 481b270..c0840ae 100644
--- a/src/components/settings/account-settings.tsx
+++ b/src/components/settings/account-settings.tsx
@@ -4,7 +4,6 @@ import { useEffect, useState } from "react";
import { useLanguage } from "@/components/language-provider";
import { LanguageSelector } from "@/components/language-selector";
import { Skeleton } from "@/components/ui/skeleton";
-import { ForwardingEmailForm } from "./forwarding-email-form";
import { MailboxSignatureForm } from "./mailbox-signature-form";
import { ProfileForm } from "./profile-form";
import { TimeZoneForm } from "./time-zone-form";
@@ -64,16 +63,6 @@ export function AccountSettings() {
initialResetEmail={user.resetEmail ?? ""}
/>
- {user.canForwardEmail && (
- <div className="space-y-4 rounded-lg bg-white p-6">
- <div>
- <h3 className="text-lg font-semibold text-neutral-900">{t("settings.account.forwardingTitle")}</h3>
- <p className="mt-1 text-sm text-neutral-500">{t("settings.account.forwardingDescription")}</p>
- </div>
- <ForwardingEmailForm initialForwardingEmail={user.forwardingEmail ?? ""} />
- </div>
- )}
-
<div className="space-y-4 rounded-b-3xl rounded-t-lg bg-white p-6">
<div>
<h3 className="text-lg font-semibold text-neutral-900">{t("settings.account.signatureTitle")}</h3>
diff --git a/src/components/settings/forwarding-email-form.tsx b/src/components/settings/forwarding-email-form.tsx
deleted file mode 100644
index b09d387..0000000
--- a/src/components/settings/forwarding-email-form.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { useLanguage } from "@/components/language-provider";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import type { ForwardingEmailFormProps } from "./types";
-import { updateForwardingEmail } from "./utils";
-
-export function ForwardingEmailForm({ initialForwardingEmail }: ForwardingEmailFormProps) {
- const { t } = useLanguage();
- const [forwardingEmail, setForwardingEmail] = useState(initialForwardingEmail);
- const [savedForwardingEmail, setSavedForwardingEmail] = useState(initialForwardingEmail);
- const [status, setStatus] = useState<string | null>(null);
- const [saving, setSaving] = useState(false);
-
- async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
- event.preventDefault();
- setSaving(true);
- setStatus(null);
- try {
- const saved = await updateForwardingEmail(forwardingEmail);
- setForwardingEmail(saved);
- setSavedForwardingEmail(saved);
- setStatus(t("common.saved"));
- } catch (error) {
- setStatus(error instanceof Error ? error.message : t("settings.forwarding.failed"));
- } finally {
- setSaving(false);
- }
- }
-
- return (
- <form onSubmit={onSubmit} className="space-y-4">
- <div className="space-y-2">
- <Label htmlFor="forwardingEmail">{t("settings.forwarding.destination")}</Label>
- <Input
- id="forwardingEmail"
- value={forwardingEmail}
- onChange={(event) => setForwardingEmail(event.target.value)}
- type="email"
- autoComplete="email"
- placeholder="[email protected]"
- />
- <p className="text-xs leading-5 text-neutral-500">
- {t("settings.forwarding.hint")}
- </p>
- </div>
- <div className="flex items-center gap-3">
- <Button type="submit" disabled={saving || forwardingEmail.trim() === savedForwardingEmail}>
- {saving ? t("common.saving") : t("settings.forwarding.save")}
- </Button>
- {status && <p role="status" className="text-sm text-neutral-500">{status}</p>}
- </div>
- </form>
- );
-}
diff --git a/src/components/settings/inbox-rules-types.d.ts b/src/components/settings/inbox-rules-types.d.ts
index c6d1b9e..31baecc 100644
--- a/src/components/settings/inbox-rules-types.d.ts
+++ b/src/components/settings/inbox-rules-types.d.ts
@@ -11,6 +11,8 @@ export type InboxRule = {
matchValue: string;
action: "store" | "forward" | "reject" | "spam" | "trash";
folderId: string | null;
+ forwardTo: string | null;
+ keepCopy: boolean;
priority: number;
};
@@ -20,6 +22,8 @@ export type InboxRuleInput = {
matchOperator: "contains" | "exact";
matchValue: string;
destination: string;
+ forwardTo?: string;
+ keepCopy?: boolean;
priority: number;
};
diff --git a/src/components/settings/inbox-rules-utils.ts b/src/components/settings/inbox-rules-utils.ts
index 08080ba..d90a640 100644
--- a/src/components/settings/inbox-rules-utils.ts
+++ b/src/components/settings/inbox-rules-utils.ts
@@ -53,6 +53,6 @@ export function getRuleOperatorLabel(operator: string, t: Translator = defaultTr
}
export function getInboxRuleDestination(rule: Pick<InboxRule, "action" | "folderId">): string {
- if (rule.action === "spam" || rule.action === "trash") return rule.action;
+ if (rule.action === "spam" || rule.action === "trash" || rule.action === "forward") return rule.action;
return rule.folderId ? `folder:${rule.folderId}` : "";
}
diff --git a/src/components/settings/inbox-rules.tsx b/src/components/settings/inbox-rules.tsx
index 47ceb0e..13da9a0 100644
--- a/src/components/settings/inbox-rules.tsx
+++ b/src/components/settings/inbox-rules.tsx
@@ -3,7 +3,7 @@
import type { FormEvent, KeyboardEvent } from "react";
import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { Folder, Plus, ShieldAlert, Trash2 } from "lucide-react";
+import { Folder, Forward, Plus, ShieldAlert, Trash2 } from "lucide-react";
import { useLanguage } from "@/components/language-provider";
import { useSelectedMailbox } from "@/components/mailbox-provider";
import { Button } from "@/components/ui/button";
@@ -15,6 +15,7 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RoutingRuleSelect } from "./domain-routing/routing-rule-select";
@@ -44,6 +45,9 @@ export function InboxRules() {
);
const [matchValue, setMatchValue] = useState("");
const [destination, setDestination] = useState("");
+ const [forwardTo, setForwardTo] = useState("");
+ const [keepCopy, setKeepCopy] = useState(false);
+ const isForward = destination === "forward";
const mailboxId = selectedMailbox?.id ?? "";
const folders = useQuery({
@@ -65,6 +69,7 @@ export function InboxRules() {
matchOperator,
matchValue,
destination,
+ ...(isForward ? { forwardTo: forwardTo.trim(), keepCopy } : {}),
priority: editingRule?.priority ?? 10,
};
return editingRule
@@ -88,8 +93,11 @@ export function InboxRules() {
);
function getRuleDestinationLabel(
- rule: Pick<InboxRule, "action" | "folderId">,
+ rule: Pick<InboxRule, "action" | "folderId" | "forwardTo" | "keepCopy">,
) {
+ if (rule.action === "forward") {
+ return t(rule.keepCopy ? "rules.forwardCopyTo" : "rules.forwardTo", { to: rule.forwardTo ?? "—" });
+ }
if (rule.action === "spam") return t("navigation.spam");
if (rule.action === "trash") return t("navigation.trash");
return folderMap.get(rule.folderId ?? "") ?? t("rules.unknownFolder");
@@ -101,6 +109,8 @@ export function InboxRules() {
setMatchOperator("contains");
setMatchValue("");
setDestination("");
+ setForwardTo("");
+ setKeepCopy(false);
save.reset();
setDialogOpen(true);
}
@@ -111,6 +121,8 @@ export function InboxRules() {
setMatchOperator(rule.matchOperator);
setMatchValue(rule.matchValue || rule.pattern);
setDestination(getInboxRuleDestination(rule));
+ setForwardTo(rule.forwardTo ?? "");
+ setKeepCopy(rule.keepCopy);
save.reset();
setDialogOpen(true);
}
@@ -161,7 +173,9 @@ export function InboxRules() {
className="group flex cursor-pointer items-center gap-3 rounded-xl bg-neutral-50 px-3 py-3 outline-none transition-colors hover:bg-neutral-100 focus-visible:ring-2 focus-visible:ring-blue-200"
>
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-blue-50 text-blue-700">
- {rule.action === "spam" ? (
+ {rule.action === "forward" ? (
+ <Forward className="h-4 w-4" />
+ ) : rule.action === "spam" ? (
<ShieldAlert className="h-4 w-4" />
) : rule.action === "trash" ? (
<Trash2 className="h-4 w-4" />
@@ -216,11 +230,12 @@ export function InboxRules() {
<RoutingRuleSelect
id="matchField"
value={matchField}
- onChange={(event) =>
- setMatchField(
- event.target.value as "email" | "content" | "title",
- )
- }
+ onChange={(event) => {
+ const next = event.target.value as "email" | "content" | "title";
+ setMatchField(next);
+ // Forwarding happens before the body is read, so it cannot match on content.
+ if (next === "content" && isForward) setDestination("");
+ }}
>
<option value="email">{t("rules.field.email")}</option>
<option value="content">{t("rules.field.content")}</option>
@@ -261,6 +276,9 @@ export function InboxRules() {
onChange={(event) => setDestination(event.target.value)}
>
<option value="">{t("rules.selectDestination")}</option>
+ {matchField !== "content" && (
+ <option value="forward">{t("rules.forwardOption")}</option>
+ )}
<option value="spam">{t("navigation.spam")}</option>
<option value="trash">{t("navigation.trash")}</option>
{(folders.data?.folders ?? []).map((folder) => (
@@ -271,6 +289,29 @@ export function InboxRules() {
</RoutingRuleSelect>
</div>
</div>
+ {isForward && (
+ <div className="grid gap-3">
+ <div className="grid min-w-0 gap-2">
+ <Label htmlFor="forwardTo">{t("rules.forwardAddress")}</Label>
+ <Input
+ id="forwardTo"
+ type="email"
+ autoComplete="email"
+ value={forwardTo}
+ onChange={(event) => setForwardTo(event.target.value)}
+ placeholder="[email protected]"
+ />
+ <p className="text-xs leading-5 text-neutral-500">{t("rules.forwardHint")}</p>
+ </div>
+ <label className="flex items-center gap-2 text-sm text-neutral-700">
+ <Checkbox
+ checked={keepCopy}
+ onChange={(event) => setKeepCopy(event.target.checked)}
+ />
+ {t("rules.forwardKeepCopy")}
+ </label>
+ </div>
+ )}
{save.isError && (
<p role="alert" className="text-sm text-red-600">{save.error.message}</p>
)}
@@ -287,6 +328,7 @@ export function InboxRules() {
disabled={
!mailboxId ||
!destination ||
+ (isForward && !forwardTo.trim()) ||
!matchValue.trim() ||
save.isPending
}
diff --git a/src/components/settings/utils.ts b/src/components/settings/utils.ts
index aa84ce2..0c60e5d 100644
--- a/src/components/settings/utils.ts
+++ b/src/components/settings/utils.ts
@@ -3,7 +3,6 @@ import { clearMailboxesCache } from "@/components/mailbox-provider-utils";
import { authFetch } from "@/lib/auth/client";
import type {
CurrentMailboxFormResponse,
- ForwardingEmailResponse,
MailboxAutoReplyResponse,
MailboxAutoReplySettings,
MailboxSignatureResponse,
@@ -55,19 +54,6 @@ export async function loadAccountSettings(): Promise<Required<AccountSettingsRes
return data.user;
}
-export async function updateForwardingEmail(forwardingEmail: string): Promise<string> {
- const res = await authFetch("/api/settings/forwarding", {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ forwardingEmail }),
- });
- const data = (await res.json()) as ForwardingEmailResponse;
- if (!res.ok) {
- throw new Error(typeof data.error === "string" ? data.error : "Failed to update forwarding email");
- }
- return data.forwardingEmail ?? "";
-}
-
export async function updateMailboxSignature(mailboxId: string, signature: string): Promise<string> {
const res = await authFetch(`/api/mailboxes/${mailboxId}`, {
method: "PATCH",
diff --git a/src/lib/email/incoming.ts b/src/lib/email/incoming.ts
index a1b4743..9edcce7 100644
--- a/src/lib/email/incoming.ts
+++ b/src/lib/email/incoming.ts
@@ -12,10 +12,15 @@ export async function resolveIncomingMail(
env: CloudflareEnv,
from: string,
to: string,
+ headers?: { subject?: string | null; alreadyForwarded?: boolean },
): Promise<RoutingDecision | null> {
try {
const db = getDb(env);
- const decision = await resolveInboundAddress(db, to, from);
+ const decision = await resolveInboundAddress(db, to, from, {
+ // A message that already went through a forward is never forwarded again by a
+ // mailbox rule, so two inboxes forwarding to each other cannot loop.
+ mailboxForwards: headers?.alreadyForwarded ? undefined : { subject: headers?.subject },
+ });
if (decision?.ruleId) {
await recordRuleMatch(db, decision.ruleId).catch(() => undefined);
}
diff --git a/src/lib/email/intake.ts b/src/lib/email/intake.ts
index 76a2cf2..610b99f 100644
--- a/src/lib/email/intake.ts
+++ b/src/lib/email/intake.ts
@@ -11,7 +11,11 @@ import type { IntakeActions, IntakeInput, IntakeResult } from "@/lib/email/intak
* callbacks, then store the raw MIME and enqueue it for parsing.
*/
export async function intakeIncomingMail(env: CloudflareEnv, input: IntakeInput, actions: IntakeActions): Promise<IntakeResult> {
- const decision = await resolveIncomingMail(env, input.from, input.to);
+ const alreadyForwarded = input.headers[MAILFLARE_FORWARDED_HEADER.toLowerCase()] === "1" || input.headers[MAILFLARE_FORWARDED_HEADER] === "1";
+ const decision = await resolveIncomingMail(env, input.from, input.to, {
+ subject: input.headers.subject,
+ alreadyForwarded,
+ });
if (decision?.action === "reject") {
const reason = decision.rejectReason ?? "Message rejected by routing rule";
@@ -26,7 +30,6 @@ export async function intakeIncomingMail(env: CloudflareEnv, input: IntakeInput,
if (forwarded && !decision.keepCopy) return { action: "forward", forwardedTo };
}
- const alreadyForwarded = input.headers[MAILFLARE_FORWARDED_HEADER.toLowerCase()] === "1" || input.headers[MAILFLARE_FORWARDED_HEADER] === "1";
if (!alreadyForwarded) {
const destination = await getAccountForwardingDestination(env, input.to);
if (destination) await actions.forward?.(destination, { [MAILFLARE_FORWARDED_HEADER]: "1" });
diff --git a/src/lib/email/routing.ts b/src/lib/email/routing.ts
index e756274..acdfe57 100644
--- a/src/lib/email/routing.ts
+++ b/src/lib/email/routing.ts
@@ -40,6 +40,14 @@ export type RuleMatchInput = {
content?: string | null;
};
+export type ResolveInboundOptions = {
+ /**
+ * Apply the mailbox owner's own forwarding rules. Only the receiving handlers set this:
+ * they can still forward the live message, and they know the subject.
+ */
+ mailboxForwards?: { subject?: string | null };
+};
+
/**
* Resolves what should happen to an inbound message addressed to `toAddress`.
*
@@ -54,6 +62,7 @@ export async function resolveInboundAddress(
db: AppDatabase,
toAddress: string,
fromAddress?: string | null,
+ options: ResolveInboundOptions = {},
): Promise<RoutingDecision | null> {
const parsed = parseRecipientAddress(toAddress);
if (!parsed) return null;
@@ -94,10 +103,20 @@ export async function resolveInboundAddress(
?? await resolveMailboxDomainAlias(db, parsed.localPart, parsed.normalizedAddress);
if (mailbox) {
- return {
- action: "store",
- mailbox: toResolvedMailbox(mailbox, domain.id, domain.hostname),
- };
+ const resolved = toResolvedMailbox(mailbox, domain.id, domain.hostname);
+ const forward = options.mailboxForwards
+ ? await findMailboxForward(db, mailbox.id, { ...matchInput, subject: options.mailboxForwards.subject })
+ : null;
+ if (forward?.forwardTo) {
+ return {
+ action: "forward",
+ forwardTo: forward.forwardTo,
+ keepCopy: forward.keepCopy,
+ mailbox: resolved,
+ ruleId: forward.id,
+ };
+ }
+ return { action: "store", mailbox: resolved };
}
// Phase 3 — catch-all and forwarding fallbacks.
@@ -127,6 +146,27 @@ export async function resolveInboundAddress(
return null;
}
+/** The first enabled forward rule of a mailbox that matches, by descending priority. */
+async function findMailboxForward(
+ db: AppDatabase,
+ mailboxId: string,
+ input: RuleMatchInput,
+): Promise<RuleRow | null> {
+ const rules = await db
+ .select()
+ .from(routingRules)
+ .where(
+ and(
+ eq(routingRules.mailboxId, mailboxId),
+ eq(routingRules.scope, "mailbox"),
+ eq(routingRules.action, "forward"),
+ eq(routingRules.enabled, true),
+ ),
+ )
+ .orderBy(desc(routingRules.priority), asc(routingRules.createdAt));
+ return rules.find((rule) => rule.forwardTo?.trim() && matchesRule(rule, input)) ?? null;
+}
+
async function listDomainRules(db: AppDatabase, domainId: string): Promise<RuleRow[]> {
return db
.select()
@@ -251,6 +291,7 @@ export async function resolveInboxRuleDestination(
.orderBy(desc(routingRules.priority), asc(routingRules.createdAt));
for (const rule of rules) {
+ if (rule.action === "forward") continue;
if (!matchesRule(rule, input)) continue;
if (rule.action === "spam" || rule.action === "trash") {
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
index a61a792..a377b4b 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -418,13 +418,12 @@
"common.cancel": "Cancel",
"common.loading": "Loading...",
"settings.account.switchInbox": "Switch inbox",
+ "settings.forwarding.hint": "Incoming mail will also be sent to this verified Cloudflare Email Routing destination.",
"settings.account.loadFailed": "Failed to load account",
"settings.account.detailsTitle": "Account details",
"settings.account.generalTitle": "General",
"settings.account.generalDescription": "Language and time zone for your account.",
"settings.account.detailsDescription": "Manage your identity, recovery options, and email preferences.",
- "settings.account.forwardingTitle": "Forwarding email",
- "settings.account.forwardingDescription": "Send a copy of incoming messages to another email address.",
"settings.account.signatureTitle": "Email signature",
"settings.account.signatureDescription": "Configure the signature for the inbox currently selected above.",
"settings.profile.updateFailed": "Failed to update account",
@@ -461,10 +460,6 @@
"settings.mailbox.title": "Settings",
"settings.mailbox.selectToView": "Select a mailbox to view its settings.",
"settings.mailbox.saveChanges": "Save changes",
- "settings.forwarding.failed": "Failed to update forwarding email",
- "settings.forwarding.destination": "Destination email",
- "settings.forwarding.hint": "Incoming mail will also be sent to this verified Cloudflare Email Routing destination.",
- "settings.forwarding.save": "Save forwarding",
"settings.signature.failed": "Failed to update signature",
"settings.signature.loadingInbox": "Loading inbox…",
"settings.signature.selectInbox": "Select an inbox to configure its signature.",
@@ -653,7 +648,7 @@
"rules.operatorOption.exact": "Exact match",
"rules.unknownFolder": "Unknown folder",
"rules.mailboxTitle": "Mailbox rules",
- "rules.appliedAfterDelivery": "Applied after delivery.",
+ "rules.appliedAfterDelivery": "Applied to mail for the selected inbox: filing after delivery, forwarding as it arrives.",
"rules.new": "New rule",
"rules.none": "No rules yet",
"rules.delete": "Delete rule",
@@ -666,6 +661,12 @@
"rules.valuePlaceholderOther": "Invoice",
"rules.destination": "Destination",
"rules.selectDestination": "Select destination",
+ "rules.forwardOption": "Forward to an address…",
+ "rules.forwardAddress": "Forward to",
+ "rules.forwardHint": "Must be a verified Cloudflare Email Routing destination. Forwarding can match the sender, recipient or title, not the message content.",
+ "rules.forwardKeepCopy": "Also keep a copy in this inbox",
+ "rules.forwardTo": "Forward to {to}",
+ "rules.forwardCopyTo": "Forward to {to} and keep a copy",
"rules.saveChanges": "Save changes",
"rules.create": "Create rule",
"routing.field.recipient": "Recipient address",
diff --git a/src/lib/validators.ts b/src/lib/validators.ts
index 3a6717c..1140cbc 100644
--- a/src/lib/validators.ts
+++ b/src/lib/validators.ts
@@ -279,7 +279,8 @@ export const routingRuleSchema = z.object({
mailboxId: z.string().min(1),
folderId: z.string().optional(),
destination: z.string().min(1).optional(),
- forwardTo: z.string().email().optional(),
+ forwardTo: z.string().trim().email().optional(),
+ keepCopy: z.boolean().optional(),
priority: z.number().int().default(0),
});
diff --git a/worker.ts b/worker.ts
index 0b6ac8b..c2bffc0 100644
--- a/worker.ts
+++ b/worker.ts
@@ -65,7 +65,10 @@ export default {
}
// Domain routing rules are resolved here rather than in the queue because reject and
// forward can only be actioned on the live ForwardableEmailMessage.
- const decision = await resolveIncomingMail(env, message.from, message.to);
+ const decision = await resolveIncomingMail(env, message.from, message.to, {
+ subject: message.headers.get("subject"),
+ alreadyForwarded: message.headers.get(MAILFLARE_FORWARDED_HEADER) === "1",
+ });
if (decision?.action === "reject") {
message.setReject(decision.rejectReason ?? "Message rejected by routing rule");