Skip to content

Email for professionals and teams

improve email attachments

Hieu Nguyen (Jack)1ae2412fcb84
diff --git a/deploy/cloudflare-email-relay/src/index.ts b/deploy/cloudflare-email-relay/src/index.ts
index 9142a68..6d2a062 100644
--- a/deploy/cloudflare-email-relay/src/index.ts
+++ b/deploy/cloudflare-email-relay/src/index.ts
@@ -24,6 +24,10 @@ async function sign(secret: string, raw: ArrayBuffer, from: string, to: string):
export default {
async email(message: ForwardableEmailMessage, env: Env) {
+ if (message.rawSize > 25 * 1024 * 1024) {
+ message.setReject("Message rejected: raw email exceeds the 25 MiB receiving limit. Send a download link instead.");
+ return;
+ }
const raw = await new Response(message.raw).arrayBuffer();
const headers = Object.fromEntries(message.headers);
let decision: Decision;
@@ -39,6 +43,10 @@ export default {
},
body: raw,
});
+ if (response.status === 413) {
+ message.setReject("Message rejected: receiving server says the email is too large. Send a download link instead.");
+ return;
+ }
if (!response.ok) throw new Error(`Mailflare answered ${response.status}`);
decision = (await response.json()) as Decision;
} catch (error) {
diff --git a/docs/api.md b/docs/api.md
index 9f0660d..414fcfa 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -88,7 +88,9 @@ To send a reply that threads correctly in the recipient's client, pass the paren
Messages composed in Mailflare are sent as HTML with a plain-text alternative derived from it. Quoted or forwarded content is wrapped in `<div class="mailflare-quote" data-mailflare-quote="1">` so the reader can fold it. `POST /api/drafts` accepts `forwardOfMessageId`, which copies that message's attachments onto the new draft; `DELETE /api/drafts/{id}/attachments/{attachmentId}` removes one, and `POST /api/send` with `draftId` sends the draft's stored files along with any uploaded in the request.
-The dashboard composer accepts up to 10 attachments, with a 10 MB limit per file and a 20 MB combined limit. Attachment metadata is stored in D1 and file content is stored in R2. Downloads require access to the mailbox containing the message.
+The dashboard composer accepts up to 10 attachments. An administrator sets the outgoing per-file and combined limit from 1 to 25 MB on **General** (`/general`); the default is 25 MB. Attachment metadata is stored in D1 and file content is stored in R2. Normal message downloads require access to the mailbox containing the message.
+Cloudflare Email Sending limits the entire encoded message, including attachments, to 5 MiB for general recipients, or 25 MiB for verified destination addresses. To stay under the general limit, files over 3 MB and smaller files that would exceed the message budget are sent as R2 download links. The recipient can download them for 30 days; anyone with the link can access the file during that time. The outgoing cap still applies to those files. Cloudflare also limits recipient count to 50, subject length to 998 characters, and headers to 16 KB.
+Incoming mail that exceeds the attachment count or 25 MB decoded attachment limit is rejected during delivery, so the sender's mail provider can report a delivery failure. Cloudflare Email Routing also limits the entire raw message to 25 MiB, including MIME encoding, and may reject it before Mailflare runs.
## JMAP
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 2234ba6..eff94fc 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -72,7 +72,7 @@ and the DNS page shows what to set by hand.
| `APP_URL` | request origin | Public URL behind a proxy |
| `SMTP_INBOUND_PORT` | `25` | Inbound SMTP; `0` disables |
| `MAIL_HOSTNAME` | `mail.<domain>` | Host the MX record points at; SMTP banner |
-| `SMTP_MAX_SIZE` | 25 MiB | Largest inbound message |
+| `SMTP_MAX_SIZE` | 36 MiB | Largest raw inbound message; allows for encoding overhead on up to 25 MB of attachments. Oversized mail receives an SMTP rejection, which the sender's mail provider can report as a delivery failure. |
| `SMTP_TLS_KEY`, `SMTP_TLS_CERT` | unset | STARTTLS certificate for the listener |
| `SMTP_URL` | unset | Outbound relay |
| `SMTP_TLS_REJECT_UNAUTHORIZED` | `true` | Trust self-signed relay certificates when `false` |
diff --git a/drizzle/migrations/0043_cloud_attachment_links.sql b/drizzle/migrations/0043_cloud_attachment_links.sql
new file mode 100644
index 0000000..e796c25
--- /dev/null
+++ b/drizzle/migrations/0043_cloud_attachment_links.sql
@@ -0,0 +1,7 @@
+ALTER TABLE app_settings ADD COLUMN outbound_attachment_max_mb integer NOT NULL DEFAULT 25;
+CREATE TABLE shared_attachment_links (
+ id text PRIMARY KEY NOT NULL,
+ attachment_id text NOT NULL UNIQUE REFERENCES message_attachments(id) ON DELETE CASCADE,
+ expires_at integer NOT NULL,
+ created_at integer NOT NULL
+);
diff --git a/server/index.ts b/server/index.ts
index 4ea35af..a196bc3 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -80,7 +80,7 @@ async function main() {
startSmtpListener(env, runtime.mailer, {
port: smtpPort,
host: process.env.SMTP_INBOUND_HOST,
- maxSize: Number(process.env.SMTP_MAX_SIZE ?? 25 * 1024 * 1024),
+ maxSize: Number(process.env.SMTP_MAX_SIZE ?? 36 * 1024 * 1024),
hostname: process.env.MAIL_HOSTNAME,
tls: process.env.SMTP_TLS_KEY && process.env.SMTP_TLS_CERT ? { keyPath: process.env.SMTP_TLS_KEY, certPath: process.env.SMTP_TLS_CERT } : null,
});
diff --git a/server/runtime/smtp.ts b/server/runtime/smtp.ts
index 5377cfd..6900355 100644
--- a/server/runtime/smtp.ts
+++ b/server/runtime/smtp.ts
@@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";
import { SMTPServer } from "smtp-server";
import type { SMTPServerSession } from "smtp-server";
import { intakeIncomingMail } from "@/lib/email/intake";
+import { inboundAttachmentLimitReasonFromRaw } from "@/lib/email/inbound-attachments";
import type { Mailer } from "./mailer";
/**
@@ -34,6 +35,18 @@ export function startSmtpListener(
return;
}
const raw = Buffer.concat(chunks);
+ let attachmentLimitReason: string | null;
+ try {
+ attachmentLimitReason = await inboundAttachmentLimitReasonFromRaw(toArrayBuffer(raw));
+ } catch (error) {
+ console.error("SMTP attachment inspection failed", error);
+ callback(Object.assign(new Error("Temporary failure, try again later"), { responseCode: 451 }));
+ return;
+ }
+ if (attachmentLimitReason) {
+ callback(Object.assign(new Error(attachmentLimitReason), { responseCode: 552 }));
+ return;
+ }
const from = session.envelope.mailFrom ? session.envelope.mailFrom.address : "";
const headers = parseHeaders(raw);
let rejectReason: string | null = null;
diff --git a/src/app/(admin)/general/page.tsx b/src/app/(admin)/general/page.tsx
new file mode 100644
index 0000000..b36ad2a
--- /dev/null
+++ b/src/app/(admin)/general/page.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { loadGeneralSettings, saveGeneralSettings } from "./utils";
+
+export default function GeneralSettingsPage() {
+ const [maxMb, setMaxMb] = useState(25);
+ const [loaded, setLoaded] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [status, setStatus] = useState("");
+
+ useEffect(() => {
+ let active = true;
+ void loadGeneralSettings().then((settings) => {
+ if (active) { setMaxMb(settings.outboundAttachmentMaxMb); setLoaded(true); }
+ }).catch((error) => { if (active) setStatus(error instanceof Error ? error.message : "Could not load settings"); });
+ return () => { active = false; };
+ }, []);
+
+ async function save(event: React.FormEvent<HTMLFormElement>) {
+ event.preventDefault();
+ setSaving(true);
+ setStatus("");
+ try {
+ const settings = await saveGeneralSettings(maxMb);
+ setMaxMb(settings.outboundAttachmentMaxMb);
+ setStatus("Attachment limit saved");
+ } catch (error) {
+ setStatus(error instanceof Error ? error.message : "Could not save settings");
+ } finally { setSaving(false); }
+ }
+
+ return <div className="space-y-6">
+ <div><h1 className="text-3xl font-medium text-neutral-900">General</h1><p className="mt-2 text-sm text-neutral-500">Set limits for outgoing mail.</p></div>
+ <Card className="rounded-3xl border-0 bg-white p-6">
+ <CardHeader className="py-0"><CardTitle>File attachments</CardTitle></CardHeader>
+ <CardContent className="pt-6"><form onSubmit={save} className="space-y-4">
+ <div className="space-y-2"><Label htmlFor="attachment-limit">Maximum attachments per email (MB)</Label><Input id="attachment-limit" type="number" min="1" max="25" step="1" value={maxMb} onChange={(event) => setMaxMb(Number(event.target.value))} disabled={!loaded || saving} className="max-w-40" required /><p className="text-sm text-neutral-500">Applies to each file and all files combined. Maximum: 25 MB; up to 10 files.</p></div>
+ <div className="space-y-2 rounded-xl bg-neutral-50 p-4 text-sm text-neutral-700"><p>Cloudflare Email Sending limits the complete email, including attachments and encoding, to 5 MiB for general recipients. The 25 MiB exception applies only to verified destination addresses.</p><p>Files over 3 MB, and smaller files that would make the email exceed Cloudflare’s 5 MiB limit, are stored in R2 and sent as download links. Links expire after 30 days. Anyone with a link can download the file until it expires. Set APP_URL to your public HTTPS address when sending through API or background workflows.</p></div>
+ {status && <p role="status" className="text-sm text-neutral-700">{status}</p>}
+ <Button type="submit" disabled={!loaded || saving || !Number.isInteger(maxMb) || maxMb < 1 || maxMb > 25}>{saving ? "Saving…" : "Save settings"}</Button>
+ </form></CardContent>
+ </Card>
+ </div>;
+}
diff --git a/src/app/(admin)/general/types.d.ts b/src/app/(admin)/general/types.d.ts
new file mode 100644
index 0000000..fd8fb06
--- /dev/null
+++ b/src/app/(admin)/general/types.d.ts
@@ -0,0 +1,3 @@
+export interface GeneralSettings {
+ outboundAttachmentMaxMb: number;
+}
diff --git a/src/app/(admin)/general/utils.ts b/src/app/(admin)/general/utils.ts
new file mode 100644
index 0000000..e0e39cc
--- /dev/null
+++ b/src/app/(admin)/general/utils.ts
@@ -0,0 +1,20 @@
+import { authFetch } from "@/lib/auth/client";
+import type { GeneralSettings } from "./types";
+
+export async function loadGeneralSettings(): Promise<GeneralSettings> {
+ const response = await authFetch("/api/admin/general", { cache: "no-store" });
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error ?? "Could not load general settings");
+ return data as GeneralSettings;
+}
+
+export async function saveGeneralSettings(outboundAttachmentMaxMb: number): Promise<GeneralSettings> {
+ const response = await authFetch("/api/admin/general", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ outboundAttachmentMaxMb }),
+ });
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error ?? "Could not save general settings");
+ return data as GeneralSettings;
+}
diff --git a/src/app/api/admin/general/route.ts b/src/app/api/admin/general/route.ts
new file mode 100644
index 0000000..b5fe44b
--- /dev/null
+++ b/src/app/api/admin/general/route.ts
@@ -0,0 +1 @@
+export { GET, PUT } from "./utils";
diff --git a/src/app/api/admin/general/utils.ts b/src/app/api/admin/general/utils.ts
new file mode 100644
index 0000000..ef2c482
--- /dev/null
+++ b/src/app/api/admin/general/utils.ts
@@ -0,0 +1,30 @@
+import { z } from "zod";
+import { getDb } from "@/db";
+import { appSettings } from "@/db/schema";
+import { getEnv } from "@/lib/cloudflare";
+import { requireSessionUser } from "@/lib/api/auth";
+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";
+import { getOutboundAttachmentMaxMb, MAX_OUTBOUND_ATTACHMENT_MAX_MB } from "@/lib/email/attachment-policy";
+
+const schema = z.object({ outboundAttachmentMaxMb: z.number().int().min(1).max(MAX_OUTBOUND_ATTACHMENT_MAX_MB) });
+
+export async function GET(request: Request) {
+ const env = getEnv();
+ const auth = await requireSessionUser(env, request);
+ if (auth.error) return auth.error;
+ if (auth.user.role !== "admin") return Response.json({ error: "Forbidden" }, { status: 403 });
+ return Response.json({ outboundAttachmentMaxMb: await getOutboundAttachmentMaxMb(env) }, { headers: { "Cache-Control": "no-store" } });
+}
+
+export async function PUT(request: Request) {
+ const env = getEnv();
+ const auth = await requireSessionUser(env, request);
+ if (auth.error) return auth.error;
+ if (auth.user.role !== "admin") return Response.json({ error: "Forbidden" }, { status: 403 });
+ if (!hasValidSessionMutationOrigin(request)) return Response.json({ error: "Invalid origin" }, { status: 403 });
+ const parsed = schema.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Choose a whole number from 1 to 25 MB" }, { status: 400 });
+ const values = { outboundAttachmentMaxMb: parsed.data.outboundAttachmentMaxMb, updatedAt: new Date() };
+ await getDb(env).insert(appSettings).values({ id: "default", ...values }).onConflictDoUpdate({ target: appSettings.id, set: values });
+ return Response.json(values, { headers: { "Cache-Control": "no-store" } });
+}
diff --git a/src/app/api/agent/approvals/[id]/confirm/route.ts b/src/app/api/agent/approvals/[id]/confirm/route.ts
index 0aa8f7c..7dfc657 100644
--- a/src/app/api/agent/approvals/[id]/confirm/route.ts
+++ b/src/app/api/agent/approvals/[id]/confirm/route.ts
@@ -10,6 +10,6 @@ export async function POST(request: Request, { params }: Params) {
const user = await getCurrentUser(env, request);
if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });
if (!hasValidSessionMutationOrigin(request)) return Response.json({ error: "Invalid origin" }, { status: 403 });
- try { return Response.json(await confirmAgentSend(env, user, (await params).id)); }
+ try { return Response.json(await confirmAgentSend(env, user, (await params).id, new URL(request.url).origin)); }
catch (error) { return Response.json({ error: error instanceof Error ? error.message : "Send could not be confirmed" }, { status: 409 }); }
}
diff --git a/src/app/api/attachment-policy/route.ts b/src/app/api/attachment-policy/route.ts
new file mode 100644
index 0000000..073d51a
--- /dev/null
+++ b/src/app/api/attachment-policy/route.ts
@@ -0,0 +1,10 @@
+import { getEnv } from "@/lib/cloudflare";
+import { requireSessionUser } from "@/lib/api/auth";
+import { CLOUD_ATTACHMENT_THRESHOLD_BYTES, getOutboundAttachmentMaxMb } from "@/lib/email/attachment-policy";
+
+export async function GET(request: Request) {
+ const env = getEnv();
+ const auth = await requireSessionUser(env, request);
+ if (auth.error) return auth.error;
+ return Response.json({ maxMb: await getOutboundAttachmentMaxMb(env), cloudThresholdBytes: CLOUD_ATTACHMENT_THRESHOLD_BYTES }, { headers: { "Cache-Control": "no-store" } });
+}
diff --git a/src/app/api/drafts/[id]/attachments/route.ts b/src/app/api/drafts/[id]/attachments/route.ts
index ee65868..5964fce 100644
--- a/src/app/api/drafts/[id]/attachments/route.ts
+++ b/src/app/api/drafts/[id]/attachments/route.ts
@@ -4,7 +4,8 @@ import { getDb } from "@/db";
import { agentDraftMetadata, messages } from "@/db/schema";
import { getCurrentUser } from "@/lib/auth/cookies";
import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";
-import { MAX_ATTACHMENT_COUNT, MAX_TOTAL_ATTACHMENT_SIZE, listMessageAttachments, storeMessageAttachments } from "@/lib/email/attachments";
+import { MAX_ATTACHMENT_COUNT, listMessageAttachments, storeMessageAttachments } from "@/lib/email/attachments";
+import { getOutboundAttachmentMaxMb } from "@/lib/email/attachment-policy";
import { readFormDataBody } from "@/lib/http/request";
import { RequestBodyTooLargeError } from "@/lib/http/errors";
import { userOwnsDraft } from "../../utils";
@@ -25,7 +26,8 @@ export async function POST(request: Request, { params }: DraftAttachmentUploadPa
const files = form.getAll("attachments").filter((value): value is File => value instanceof File && value.size > 0);
if (!files.length) return Response.json({ error: "No attachments provided" }, { status: 400 });
const existing = await listMessageAttachments(env, id);
- if (existing.length + files.length > MAX_ATTACHMENT_COUNT || existing.reduce((total, file) => total + file.size, 0) + files.reduce((total, file) => total + file.size, 0) > MAX_TOTAL_ATTACHMENT_SIZE) return Response.json({ error: "Draft attachments exceed the allowed count or total size" }, { status: 400 });
+ const maxBytes = (await getOutboundAttachmentMaxMb(env)) * 1_000_000;
+ if (existing.length + files.length > MAX_ATTACHMENT_COUNT || files.some((file) => file.size > maxBytes) || existing.reduce((total, file) => total + file.size, 0) + files.reduce((total, file) => total + file.size, 0) > maxBytes) return Response.json({ error: "Draft attachments exceed the allowed count or outgoing size limit" }, { status: 400 });
try {
const attachments = await storeMessageAttachments(env, id, await Promise.all(files.map(async (file) => ({ filename: file.name, type: file.type || "application/octet-stream", content: await file.arrayBuffer(), disposition: "attachment" as const }))));
await db.update(agentDraftMetadata).set({ revision: sql`${agentDraftMetadata.revision} + 1`, humanEditedAt: new Date() }).where(eq(agentDraftMetadata.draftId, id));
diff --git a/src/app/api/inbound/route.ts b/src/app/api/inbound/route.ts
index f921222..f02a7a7 100644
--- a/src/app/api/inbound/route.ts
+++ b/src/app/api/inbound/route.ts
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { getEnv } from "@/lib/cloudflare";
import { intakeIncomingMail } from "@/lib/email/intake";
import { verifyInboundSignature } from "@/lib/email/intake-signature";
+import { inboundAttachmentLimitReasonFromRaw } from "@/lib/email/inbound-attachments";
export const dynamic = "force-dynamic";
@@ -17,13 +18,15 @@ export async function POST(request: Request) {
if (!secret) return NextResponse.json({ error: "INBOUND_WEBHOOK_SECRET is not configured" }, { status: 503 });
const raw = await request.arrayBuffer();
- if (raw.byteLength > 25 * 1024 * 1024) return NextResponse.json({ error: "Message too large" }, { status: 413 });
+ if (raw.byteLength > 25 * 1024 * 1024) return NextResponse.json({ error: "Message exceeds the 25 MiB receiving limit" }, { status: 413 });
const from = request.headers.get("x-mailflare-from") ?? "";
const to = request.headers.get("x-mailflare-to") ?? "";
const signature = request.headers.get("x-mailflare-signature") ?? "";
if (!from || !to || !(await verifyInboundSignature(secret, signature, raw, from, to))) {
return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
}
+ const attachmentLimitReason = await inboundAttachmentLimitReasonFromRaw(raw);
+ if (attachmentLimitReason) return NextResponse.json({ action: "reject", reason: attachmentLimitReason });
let headers: Record<string, string> = {};
try {
diff --git a/src/app/api/send/error-utils.ts b/src/app/api/send/error-utils.ts
index afbef9b..bec3d67 100644
--- a/src/app/api/send/error-utils.ts
+++ b/src/app/api/send/error-utils.ts
@@ -1,5 +1,6 @@
export function getSendErrorStatus(message: string): number {
if (message === "Mailbox is required") return 400;
+ if (message.startsWith("Attachments exceed") || message.startsWith("Subject exceeds") || message.startsWith("Headers exceed") || message.startsWith("Message exceeds Cloudflare") || message.startsWith("A message can include at most") || message.includes("exceeds the 25 MB attachment limit")) return 400;
if (
message === "Mailbox not found" ||
message === "Sender account not found" ||
diff --git a/src/app/api/send/route.ts b/src/app/api/send/route.ts
index b208cb7..0f2cc43 100644
--- a/src/app/api/send/route.ts
+++ b/src/app/api/send/route.ts
@@ -46,6 +46,7 @@ export async function POST(request: Request) {
userId: user.id,
...parsed.data,
attachments,
+ publicOrigin: new URL(request.url).origin,
});
return NextResponse.json(result);
} catch (err) {
diff --git a/src/app/api/shared-files/[id]/route.ts b/src/app/api/shared-files/[id]/route.ts
new file mode 100644
index 0000000..0c011db
--- /dev/null
+++ b/src/app/api/shared-files/[id]/route.ts
@@ -0,0 +1,29 @@
+import { and, eq, gt } from "drizzle-orm";
+import { getDb } from "@/db";
+import { messageAttachments, sharedAttachmentLinks } from "@/db/schema";
+import { getEnv } from "@/lib/cloudflare";
+import { getAttachmentContentDisposition } from "@/app/api/messages/[messageId]/attachments/[attachmentId]/utils";
+import type { SharedFileParams } from "./types";
+
+export async function GET(_request: Request, { params }: SharedFileParams) {
+ const { id } = await params;
+ const env = getEnv();
+ const [file] = await getDb(env)
+ .select({ r2Key: messageAttachments.r2Key, filename: messageAttachments.filename, size: messageAttachments.size, contentType: messageAttachments.contentType })
+ .from(sharedAttachmentLinks)
+ .innerJoin(messageAttachments, eq(sharedAttachmentLinks.attachmentId, messageAttachments.id))
+ .where(and(eq(sharedAttachmentLinks.id, id), gt(sharedAttachmentLinks.expiresAt, new Date())))
+ .limit(1);
+ if (!file) return new Response("Link expired or not found", { status: 404 });
+ const object = await env.BUCKET.get(file.r2Key);
+ if (!object) return new Response("File not found", { status: 404 });
+ const headers = new Headers();
+ headers.set("Content-Type", file.contentType);
+ headers.set("Content-Length", String(file.size));
+ headers.set("Content-Disposition", getAttachmentContentDisposition(file.filename, false));
+ headers.set("X-Content-Type-Options", "nosniff");
+ headers.set("Content-Security-Policy", "default-src 'none'; sandbox");
+ headers.set("Referrer-Policy", "no-referrer");
+ headers.set("Cache-Control", "private, no-store");
+ return new Response(object.body, { headers });
+}
diff --git a/src/app/api/shared-files/[id]/types.d.ts b/src/app/api/shared-files/[id]/types.d.ts
new file mode 100644
index 0000000..ccd3b4b
--- /dev/null
+++ b/src/app/api/shared-files/[id]/types.d.ts
@@ -0,0 +1 @@
+export type SharedFileParams = { params: Promise<{ id: string }> };
diff --git a/src/app/api/v1/send/route.ts b/src/app/api/v1/send/route.ts
index 1e0f746..2cf7b71 100644
--- a/src/app/api/v1/send/route.ts
+++ b/src/app/api/v1/send/route.ts
@@ -17,7 +17,7 @@ export async function POST(request: Request) {
let body: unknown;
try {
- body = await readJsonBody(request, 30 * 1024 * 1024);
+ body = await readJsonBody(request, 40 * 1024 * 1024);
} catch (error) {
const status = error instanceof RequestBodyTooLargeError ? 413 : 400;
return NextResponse.json({ error: "Invalid send request" }, { status });
@@ -35,6 +35,7 @@ export async function POST(request: Request) {
const result = await sendEmail(env, {
userId: auth.userId,
...fields,
+ publicOrigin: new URL(request.url).origin,
attachments: attachments?.map((attachment) => ({
filename: attachment.filename,
type: attachment.type,
diff --git a/src/components/admin-nav.tsx b/src/components/admin-nav.tsx
index c732706..0f33075 100644
--- a/src/components/admin-nav.tsx
+++ b/src/components/admin-nav.tsx
@@ -38,6 +38,7 @@ const sections = [
{
label: "Administration",
links: [
+ { href: "/general", label: "General", icon: Settings },
{ href: "/agent", label: "Agent", icon: Bot },
{ href: "/accounts", label: "Accounts", icon: Users },
{ href: "/activity", label: "Activity", icon: Activity },
diff --git a/src/components/compose/attachment-policy-types.d.ts b/src/components/compose/attachment-policy-types.d.ts
new file mode 100644
index 0000000..136942b
--- /dev/null
+++ b/src/components/compose/attachment-policy-types.d.ts
@@ -0,0 +1,4 @@
+export interface ComposeAttachmentPolicy {
+ maxMb: number;
+ cloudThresholdBytes: number;
+}
diff --git a/src/components/compose/compose-form.tsx b/src/components/compose/compose-form.tsx
index 961fa9c..024f6b9 100644
--- a/src/components/compose/compose-form.tsx
+++ b/src/components/compose/compose-form.tsx
@@ -29,6 +29,7 @@ import {
} from "./rich-text-utils";
import { headerToRecipients, isValidRecipient, recipientsToHeader } from "./recipient-utils";
import type { ComposeAttachment, ComposeStoredAttachment, ComposeThreading } from "./types";
+import type { ComposeAttachmentPolicy } from "./attachment-policy-types";
type Toast = { type: "success" | "error"; message: string } | null;
@@ -59,6 +60,7 @@ export function ComposeForm({
const [attachments, setAttachments] = useState<ComposeAttachment[]>([]);
// Attachments the draft already holds server-side (a forwarded message's files).
const [storedAttachments, setStoredAttachments] = useState<ComposeStoredAttachment[]>([]);
+ const [attachmentPolicy, setAttachmentPolicy] = useState<ComposeAttachmentPolicy>({ maxMb: 25, cloudThresholdBytes: 3_000_000 });
const [draggingFiles, setDraggingFiles] = useState(false);
const [modalMode, setModalMode] = useState(false);
const [toast, setToast] = useState<Toast>(null);
@@ -79,6 +81,14 @@ export function ComposeForm({
if (!selectedMailbox && mailboxes.length === 1) setSelectedMailbox(mailboxes[0]);
}, [mailboxes, selectedMailbox, setSelectedMailbox]);
+ useEffect(() => {
+ let active = true;
+ void authFetch("/api/attachment-policy", { cache: "no-store" }).then(async (response) => {
+ if (response.ok && active) setAttachmentPolicy((await response.json()) as ComposeAttachmentPolicy);
+ }).catch(() => {});
+ return () => { active = false; };
+ }, []);
+
const senderAddresses = useMemo(() => {
if (!selectedMailbox) return [];
return selectedMailbox.senderAddresses?.length
@@ -376,12 +386,12 @@ export function ComposeForm({
setToast({ type: "error", message: "A message can include at most 10 attachments" });
return;
}
- if (nextFiles.some((file) => file.size > 10 * 1024 * 1024)) {
- setToast({ type: "error", message: "Each attachment must be 10 MB or smaller" });
+ if (nextFiles.some((file) => file.size > attachmentPolicy.maxMb * 1_000_000)) {
+ setToast({ type: "error", message: `Each attachment must be ${attachmentPolicy.maxMb} MB or smaller` });
return;
}
- if (totalSize > 20 * 1024 * 1024) {
- setToast({ type: "error", message: "Attachments must total 20 MB or less" });
+ if (totalSize > attachmentPolicy.maxMb * 1_000_000) {
+ setToast({ type: "error", message: `Attachments must total ${attachmentPolicy.maxMb} MB or less` });
return;
}
@@ -426,6 +436,7 @@ export function ComposeForm({
}
const attachmentContent = (attachments.length > 0 || storedAttachments.length > 0) && (
+ <div>
<div className="flex min-w-0 flex-nowrap gap-2 overflow-x-auto overflow-y-hidden px-3 py-2">
{storedAttachments.map((attachment) => (
<div
@@ -471,6 +482,8 @@ export function ComposeForm({
</div>
))}
</div>
+ <p className="px-3 pb-2 text-xs text-amber-700">Cloudflare limits general email messages to 5 MiB including encoding. Files over 3 MB{([...attachments.map((item) => item.file.size), ...storedAttachments.map((item) => item.size)].some((size) => size > attachmentPolicy.cloudThresholdBytes)) ? " here will" : " or files that exceed the message budget may"} be sent as 30-day R2 download links.</p>
+ </div>
);
const frameClass =
@@ -638,7 +651,7 @@ export function ComposeForm({
className="hidden"
onChange={(event) => addAttachments(event.target.files)}
/>
- <Tooltip label="Attach files">
+ <Tooltip label={`Attach files (up to ${attachmentPolicy.maxMb} MB total). Files over 3 MB are sent as 30-day R2 download links.`}>
<button
type="button"
aria-label="Attach files"
diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts
index 4543cb0..0dfc774 100644
--- a/src/db/schema/index.ts
+++ b/src/db/schema/index.ts
@@ -331,6 +331,13 @@ export const messageAttachments = sqliteTable(
(t) => [index("message_attachments_message_idx").on(t.messageId)],
);
+export const sharedAttachmentLinks = sqliteTable("shared_attachment_links", {
+ id: text("id").primaryKey(),
+ attachmentId: text("attachment_id").notNull().references(() => messageAttachments.id, { onDelete: "cascade" }).unique(),
+ expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),
+});
+
export const outboundJobs = sqliteTable("outbound_jobs", {
id: text("id").primaryKey(),
userId: text("user_id")
@@ -576,6 +583,7 @@ export const backupSettings = sqliteTable("backup_settings", {
export const appSettings = sqliteTable("app_settings", {
id: text("id").primaryKey(),
appName: text("app_name").notNull().default("Mailflare"),
+ outboundAttachmentMaxMb: integer("outbound_attachment_max_mb").notNull().default(25),
iconKey: text("icon_key"),
agentEnabled: integer("agent_enabled", { mode: "boolean" }).notNull().default(true),
agentProvider: text("agent_provider", { enum: ["cloudflare", "compatible"] }),
@@ -734,6 +742,7 @@ export const schema = {
spamReputation,
spamFeedback,
messageAttachments,
+ sharedAttachmentLinks,
outboundJobs,
emailTemplates,
calendarEvents,
diff --git a/src/lib/agent/approvals/utils.ts b/src/lib/agent/approvals/utils.ts
index 77926fb..8b105f1 100644
--- a/src/lib/agent/approvals/utils.ts
+++ b/src/lib/agent/approvals/utils.ts
@@ -72,7 +72,7 @@ export async function getAgentSendRequest(env: CloudflareEnv, user: SessionUser,
return { approvalId, status: approval.status, draftId: approval.draftId, messageId: approval.messageId, expiresAt: approval.expiresAt, snapshot: current, stale };
}
-export async function confirmAgentSend(env: CloudflareEnv, user: SessionUser, approvalId: string) {
+export async function confirmAgentSend(env: CloudflareEnv, user: SessionUser, approvalId: string, publicOrigin?: string) {
const db = getDb(env);
const [approval] = await db.select().from(agentSendApprovals).where(and(eq(agentSendApprovals.id, approvalId), eq(agentSendApprovals.userId, user.id))).limit(1);
if (!approval) throw new Error("Approval not found");
@@ -95,6 +95,7 @@ export async function confirmAgentSend(env: CloudflareEnv, user: SessionUser, ap
inReplyTo: draft.inReplyTo, references: draft.references, threadId: draft.threadId,
attachments: await loadMessageAttachmentContents(env, draft.id),
scheduledAt: metadata.scheduledAt ?? undefined,
+ publicOrigin,
});
await db.update(agentSendApprovals).set({ status: "sent", messageId: result.messageId }).where(eq(agentSendApprovals.id, approvalId));
await db.update(messages).set({ status: "trash" }).where(and(eq(messages.id, draft.id), eq(messages.status, "draft")));
diff --git a/src/lib/email/attachment-policy.ts b/src/lib/email/attachment-policy.ts
new file mode 100644
index 0000000..6a48b67
--- /dev/null
+++ b/src/lib/email/attachment-policy.ts
@@ -0,0 +1,16 @@
+import { eq } from "drizzle-orm";
+import { getDb } from "@/db";
+import { appSettings } from "@/db/schema";
+
+export const DEFAULT_OUTBOUND_ATTACHMENT_MAX_MB = 25;
+export const MAX_OUTBOUND_ATTACHMENT_MAX_MB = 25;
+export const CLOUD_ATTACHMENT_THRESHOLD_BYTES = 3_000_000;
+
+export async function getOutboundAttachmentMaxMb(env: CloudflareEnv): Promise<number> {
+ const [settings] = await getDb(env)
+ .select({ maxMb: appSettings.outboundAttachmentMaxMb })
+ .from(appSettings)
+ .where(eq(appSettings.id, "default"))
+ .limit(1);
+ return settings?.maxMb ?? DEFAULT_OUTBOUND_ATTACHMENT_MAX_MB;
+}
diff --git a/src/lib/email/attachment-types.d.ts b/src/lib/email/attachment-types.d.ts
index ccb888e..8274731 100644
--- a/src/lib/email/attachment-types.d.ts
+++ b/src/lib/email/attachment-types.d.ts
@@ -1,5 +1,6 @@
export interface AttachmentContent {
content: ArrayBuffer;
+ storageId?: string;
contentId?: string | null;
disposition?: "attachment" | "inline";
filename: string;
diff --git a/src/lib/email/attachments.ts b/src/lib/email/attachments.ts
index 29db1b2..19c291e 100644
--- a/src/lib/email/attachments.ts
+++ b/src/lib/email/attachments.ts
@@ -10,8 +10,8 @@ import type {
StoredAttachment,
} from "./attachment-types";
-export const MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024;
-export const MAX_TOTAL_ATTACHMENT_SIZE = 20 * 1024 * 1024;
+export const MAX_ATTACHMENT_SIZE = 25_000_000;
+export const MAX_TOTAL_ATTACHMENT_SIZE = 25_000_000;
export const MAX_ATTACHMENT_COUNT = 10;
export function decodeBase64Content(content: string): ArrayBuffer {
@@ -49,13 +49,13 @@ export function validateAttachments(attachments: AttachmentContent[]): void {
for (const attachment of attachments) {
const size = attachment.content.byteLength;
if (size > MAX_ATTACHMENT_SIZE) {
- throw new Error(`${attachment.filename} exceeds the 10 MB attachment limit`);
+ throw new Error(`${attachment.filename} exceeds the 25 MB attachment limit`);
}
totalSize += size;
}
if (totalSize > MAX_TOTAL_ATTACHMENT_SIZE) {
- throw new Error("Attachments exceed the 20 MB total limit");
+ throw new Error("Attachments exceed the 25 MB total limit");
}
}
@@ -166,6 +166,7 @@ export async function loadMessageAttachmentContents(
const object = await env.BUCKET.get(row.r2Key);
if (!object) continue;
result.push({
+ storageId: row.id,
filename: row.filename,
type: row.contentType,
content: await object.arrayBuffer(),
diff --git a/src/lib/email/cloud-attachment-utils.ts b/src/lib/email/cloud-attachment-utils.ts
new file mode 100644
index 0000000..d4fbf07
--- /dev/null
+++ b/src/lib/email/cloud-attachment-utils.ts
@@ -0,0 +1,45 @@
+import type { AttachmentContent } from "./attachment-types";
+import { CLOUD_ATTACHMENT_THRESHOLD_BYTES } from "./attachment-policy";
+import { getOrCreateSharedAttachmentUrl } from "./shared-attachments";
+
+const GENERAL_MESSAGE_LIMIT_BYTES = 5 * 1024 * 1024;
+const MIME_SAFETY_MARGIN_BYTES = 256 * 1024;
+
+function escapeHtml(value: string): string {
+ return value.replace(/[&<>"']/g, (character) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[character] ?? character);
+}
+
+export async function prepareCloudflareAttachments(
+ env: CloudflareEnv,
+ attachments: AttachmentContent[],
+ message: { subject: string; html?: string; text?: string; headers: Record<string, string>; publicOrigin?: string },
+): Promise<{ attachments: AttachmentContent[]; html?: string; text?: string }> {
+ const encoder = new TextEncoder();
+ let estimatedSize = encoder.encode(message.subject + (message.html ?? "") + (message.text ?? "") + JSON.stringify(message.headers)).byteLength + 8192;
+ const direct: AttachmentContent[] = [];
+ const linked: { filename: string; size: number; url: string }[] = [];
+ for (const attachment of attachments) {
+ const size = attachment.content.byteLength;
+ const encodedSize = Math.ceil(size / 3) * 4 + 2048;
+ if (size <= CLOUD_ATTACHMENT_THRESHOLD_BYTES && estimatedSize + encodedSize <= GENERAL_MESSAGE_LIMIT_BYTES - MIME_SAFETY_MARGIN_BYTES) {
+ direct.push(attachment);
+ estimatedSize += encodedSize;
+ continue;
+ }
+ if (!attachment.storageId) throw new Error("Large attachment was not stored in R2");
+ linked.push({ filename: attachment.filename, size, url: await getOrCreateSharedAttachmentUrl(env, attachment.storageId, message.publicOrigin) });
+ }
+ if (!linked.length) {
+ if (estimatedSize > GENERAL_MESSAGE_LIMIT_BYTES - MIME_SAFETY_MARGIN_BYTES) throw new Error("Message exceeds Cloudflare's 5 MiB email size limit");
+ return { attachments: direct, html: message.html, text: message.text };
+ }
+ const intro = "Files shared through Mailflare (download links expire after 30 days):";
+ const textLinks = linked.map((file) => `${file.filename} (${(file.size / 1_000_000).toFixed(1)} MB): ${file.url}`).join("\n");
+ const htmlLinks = linked.map((file) => `<li>${escapeHtml(file.filename)} (${(file.size / 1_000_000).toFixed(1)} MB): <a href="${escapeHtml(file.url)}">Download file</a></li>`).join("");
+ const text = [message.text?.trim(), intro, textLinks].filter(Boolean).join("\n\n");
+ const html = `${message.html ?? ""}<div><p>${escapeHtml(intro)}</p><ul>${htmlLinks}</ul></div>`;
+ if (estimatedSize + encoder.encode(textLinks + htmlLinks + intro + intro).byteLength + 4096 > GENERAL_MESSAGE_LIMIT_BYTES - MIME_SAFETY_MARGIN_BYTES) {
+ throw new Error("Message exceeds Cloudflare's 5 MiB email size limit even with download links");
+ }
+ return { attachments: direct, html, text };
+}
diff --git a/src/lib/email/inbound-attachments.ts b/src/lib/email/inbound-attachments.ts
index d10f3c2..1acc086 100644
--- a/src/lib/email/inbound-attachments.ts
+++ b/src/lib/email/inbound-attachments.ts
@@ -3,17 +3,28 @@ import {
MAX_ATTACHMENT_SIZE,
MAX_TOTAL_ATTACHMENT_SIZE,
} from "@/lib/email/attachments";
+import { parseRawMime } from "@/lib/email/parse";
import type { AttachmentContent } from "@/lib/email/attachment-types";
-export function selectInboundAttachments(attachments: AttachmentContent[]): AttachmentContent[] {
- const selected: AttachmentContent[] = [];
+export function inboundAttachmentLimitReason(attachments: AttachmentContent[]): string | null {
+ if (attachments.length > MAX_ATTACHMENT_COUNT) {
+ return `Message rejected: more than ${MAX_ATTACHMENT_COUNT} attachments. Send fewer files or a download link.`;
+ }
let totalSize = 0;
for (const attachment of attachments) {
const size = attachment.content.byteLength;
- if (selected.length >= MAX_ATTACHMENT_COUNT) break;
- if (size > MAX_ATTACHMENT_SIZE || totalSize + size > MAX_TOTAL_ATTACHMENT_SIZE) continue;
- selected.push(attachment);
+ if (size > MAX_ATTACHMENT_SIZE) {
+ return "Message rejected: an attachment exceeds 25 MB. Send a download link instead.";
+ }
totalSize += size;
+ if (totalSize > MAX_TOTAL_ATTACHMENT_SIZE) {
+ return "Message rejected: attachments exceed 25 MB in total. Send a download link instead.";
+ }
}
- return selected;
+ return null;
+}
+
+export async function inboundAttachmentLimitReasonFromRaw(raw: ArrayBuffer): Promise<string | null> {
+ const parsed = await parseRawMime(raw);
+ return inboundAttachmentLimitReason(parsed.attachments);
}
diff --git a/src/lib/email/inbound.ts b/src/lib/email/inbound.ts
index ecc999f..d367737 100644
--- a/src/lib/email/inbound.ts
+++ b/src/lib/email/inbound.ts
@@ -10,7 +10,7 @@ import { getEmailAddress } from "@/lib/email/address";
import { sendMailboxAutoReply } from "@/lib/email/auto-reply";
import { getMailboxAccessLevel } from "@/lib/mailboxes/access";
import { listMessageAttachments, storeMessageAttachments } from "@/lib/email/attachments";
-import { selectInboundAttachments } from "@/lib/email/inbound-attachments";
+import { inboundAttachmentLimitReason } from "@/lib/email/inbound-attachments";
import { inboundMessageId } from "@/lib/email/inbound-id";
import { getUnsubscribeUrlFromRawR2Key } from "@/lib/email/unsubscribe";
import { resolveThreadId } from "@/lib/email/threading";
@@ -78,6 +78,12 @@ export async function processInboundMessage(
const buffer = await raw.arrayBuffer();
const parsed = await parseRawMime(buffer);
+ const attachmentLimitReason = inboundAttachmentLimitReason(parsed.attachments);
+ if (attachmentLimitReason) {
+ console.warn(`Inbound attachment limit reached for ${payload.to}: ${attachmentLimitReason}`);
+ await env.BUCKET.delete(payload.rawR2Key);
+ return;
+ }
const messageId = await inboundMessageId(payload.rawR2Key);
const snippet = buildSnippet(parsed.text, parsed.html);
const deliveredAddress = getEmailAddress(payload.to) || `${decision.mailbox.localPart}@${decision.mailbox.hostname}`;
@@ -161,11 +167,7 @@ export async function processInboundMessage(
}).onConflictDoNothing().returning({ id: messages.id });
if (!inserted.length) return;
- const attachments = selectInboundAttachments(parsed.attachments);
- if (attachments.length !== parsed.attachments.length) {
- console.warn(`Inbound attachment limits omitted ${parsed.attachments.length - attachments.length} files for ${messageId}`);
- }
- await storeMessageAttachments(env, messageId, attachments);
+ await storeMessageAttachments(env, messageId, parsed.attachments);
if (spamAnalysis) {
try {
await recordReputationObservation(env, decision.mailbox.mailboxId, getReputationKeys(parsed, spamAnalysis.fingerprint));
@@ -233,11 +235,10 @@ export async function storeRawToR2(
env: CloudflareEnv,
from: string,
to: string,
- raw: ReadableStream<Uint8Array>,
+ raw: ArrayBuffer,
): Promise<string> {
const key = `inbound/${Date.now()}-${newId()}.eml`;
- const buffer = await new Response(raw).arrayBuffer();
- await env.BUCKET.put(key, buffer, {
+ await env.BUCKET.put(key, raw, {
httpMetadata: { contentType: "message/rfc822" },
customMetadata: { from, to },
});
diff --git a/src/lib/email/send.ts b/src/lib/email/send.ts
index f637c08..924b73a 100644
--- a/src/lib/email/send.ts
+++ b/src/lib/email/send.ts
@@ -11,6 +11,8 @@ import { formatMessageIdHeader, normalizeMessageId, parseMessageIdList } from "@
import { createAuditLog } from "@/lib/mailboxes/audit";
import { loadMessageAttachmentContents, storeMessageAttachments, validateAttachments } from "@/lib/email/attachments";
import type { AttachmentContent } from "@/lib/email/attachment-types";
+import { getOutboundAttachmentMaxMb } from "@/lib/email/attachment-policy";
+import { prepareCloudflareAttachments } from "@/lib/email/cloud-attachment-utils";
export type SendEmailInput = {
userId: string;
@@ -33,6 +35,7 @@ export type SendEmailInput = {
attachments?: AttachmentContent[];
/** Future delivery time. Values at or before the current time send immediately. */
scheduledAt?: string | Date;
+ publicOrigin?: string;
};
const MAX_RECIPIENTS = 50;
@@ -72,6 +75,13 @@ export async function sendEmail(
const sender = await getAuthorizedSenderAddress(env, input);
const attachments = input.attachments ?? [];
validateAttachments(attachments);
+ const maxAttachmentMb = await getOutboundAttachmentMaxMb(env);
+ const maxAttachmentBytes = maxAttachmentMb * 1_000_000;
+ if (attachments.some((attachment) => attachment.content.byteLength > maxAttachmentBytes) ||
+ attachments.reduce((total, attachment) => total + attachment.content.byteLength, 0) > maxAttachmentBytes) {
+ throw new Error(`Attachments exceed the administrator's ${maxAttachmentMb} MB outgoing limit`);
+ }
+ if (input.subject.length > 998) throw new Error("Subject exceeds Cloudflare's 998-character limit");
const to = toRecipientList(input.to);
const cc = toRecipientList(input.cc);
@@ -91,6 +101,9 @@ export async function sendEmail(
const headers: Record<string, string> = { ...input.headers };
if (inReplyTo) headers["In-Reply-To"] = `<${inReplyTo}>`;
if (references.length > 0) headers.References = formatMessageIdHeader(references);
+ if (new TextEncoder().encode(Object.entries(headers).map(([name, value]) => `${name}: ${value}\r\n`).join("")).byteLength > 16 * 1024) {
+ throw new Error("Headers exceed Cloudflare's 16 KB limit");
+ }
const messageId = newId("msg");
const requestedSchedule = input.scheduledAt ? new Date(input.scheduledAt) : null;
@@ -119,7 +132,8 @@ export async function sendEmail(
references: references.length ? references.join(" ") : null,
});
try {
- await storeMessageAttachments(env, messageId, attachments);
+ const stored = await storeMessageAttachments(env, messageId, attachments);
+ stored.forEach((attachment, index) => { attachments[index].storageId = attachment.id; });
} catch (error) {
await db.delete(messages).where(eq(messages.id, messageId));
throw error;
@@ -169,6 +183,16 @@ async function deliverEmail(env: CloudflareEnv, delivery: PreparedDelivery): Pro
const db = getDb(env);
const toAddr = joinEmailAddressList(to);
try {
+ const prepared = await prepareCloudflareAttachments(env, attachments, {
+ subject: input.subject,
+ html: input.html,
+ text: input.text,
+ headers,
+ publicOrigin: input.publicOrigin,
+ });
+ if (prepared.text !== input.text || prepared.html !== input.html) {
+ await db.update(messages).set({ textBody: prepared.text ?? null, htmlBody: prepared.html ?? null }).where(eq(messages.id, messageId));
+ }
const response = await env.EMAIL.send({
from,
to,
@@ -176,9 +200,9 @@ async function deliverEmail(env: CloudflareEnv, delivery: PreparedDelivery): Pro
...(bcc.length ? { bcc } : {}),
subject: input.subject,
headers: Object.keys(headers).length ? headers : undefined,
- html: input.html,
- text: input.text,
- attachments: attachments.map((attachment) =>
+ html: prepared.html,
+ text: prepared.text,
+ attachments: prepared.attachments.map((attachment) =>
attachment.disposition === "inline" && attachment.contentId
? {
filename: attachment.filename,
diff --git a/src/lib/email/shared-attachments.ts b/src/lib/email/shared-attachments.ts
new file mode 100644
index 0000000..a8233bf
--- /dev/null
+++ b/src/lib/email/shared-attachments.ts
@@ -0,0 +1,31 @@
+import { and, eq, lte } from "drizzle-orm";
+import { getDb } from "@/db";
+import { sharedAttachmentLinks } from "@/db/schema";
+import { newId } from "@/lib/ids";
+
+export const SHARED_ATTACHMENT_LINK_DAYS = 30;
+
+export async function getOrCreateSharedAttachmentUrl(
+ env: CloudflareEnv,
+ attachmentId: string,
+ publicOrigin?: string,
+): Promise<string> {
+ const origin = env.APP_URL?.trim() || publicOrigin;
+ if (!origin) throw new Error("Set APP_URL before sending large attachments as download links");
+ const url = new URL(origin);
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
+ throw new Error("A public HTTPS APP_URL is required for large attachment links");
+ }
+ const db = getDb(env);
+ const now = new Date();
+ await db.delete(sharedAttachmentLinks).where(and(eq(sharedAttachmentLinks.attachmentId, attachmentId), lte(sharedAttachmentLinks.expiresAt, now)));
+ const id = newId("share");
+ await db.insert(sharedAttachmentLinks).values({
+ id,
+ attachmentId,
+ expiresAt: new Date(now.getTime() + SHARED_ATTACHMENT_LINK_DAYS * 24 * 60 * 60_000),
+ }).onConflictDoNothing();
+ const [link] = await db.select({ id: sharedAttachmentLinks.id }).from(sharedAttachmentLinks).where(eq(sharedAttachmentLinks.attachmentId, attachmentId)).limit(1);
+ if (!link) throw new Error("Could not create a large attachment link");
+ return new URL(`/api/shared-files/${encodeURIComponent(link.id)}`, url).toString();
+}
diff --git a/src/lib/jmap/identities.ts b/src/lib/jmap/identities.ts
index 9d145ec..99c8ba2 100644
--- a/src/lib/jmap/identities.ts
+++ b/src/lib/jmap/identities.ts
@@ -92,6 +92,7 @@ export const emailSubmissionSet: JmapMethodHandler = async (ctx, args) => {
threadId: draft.threadId,
mailboxId: identity.mailboxId,
attachments,
+ publicOrigin: ctx.origin,
});
try {
await deleteMessageWithObjects(ctx.env, ctx.db, draft.id, draft.rawR2Key);
diff --git a/worker.ts b/worker.ts
index b086872..641cf55 100644
--- a/worker.ts
+++ b/worker.ts
@@ -11,6 +11,7 @@ import { processWebhookRetry, type WebhookRetryMessage } from "./src/lib/email/w
import { resolveIncomingMail, forwardMessage } from "./src/lib/email/incoming";
import { getUserFromSession } from "./src/lib/auth/session";
import { getSessionTokenFromRequest } from "./src/lib/realtime/utils";
+import { inboundAttachmentLimitReasonFromRaw } from "./src/lib/email/inbound-attachments";
import { hasValidSessionMutationOrigin } from "./src/lib/auth/origin";
import {
getAccountForwardingDestination,
@@ -48,6 +49,10 @@ export default {
async email(message: ForwardableEmailMessage, env: CloudflareEnv, ctx: ExecutionContext) {
try {
+ if (message.rawSize > 25 * 1024 * 1024) {
+ message.setReject("Message rejected: raw email exceeds the 25 MiB receiving limit. Send a download link instead.");
+ return;
+ }
// 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);
@@ -56,6 +61,12 @@ export default {
message.setReject(decision.rejectReason ?? "Message rejected by routing rule");
return;
}
+ const raw = await new Response(message.raw).arrayBuffer();
+ const attachmentLimitReason = await inboundAttachmentLimitReasonFromRaw(raw);
+ if (attachmentLimitReason) {
+ message.setReject(attachmentLimitReason);
+ return;
+ }
if (decision?.action === "forward" && decision.forwardTo) {
const forwarded = await forwardMessage(message, decision.forwardTo);
@@ -70,7 +81,7 @@ export default {
await forwardMessage(message, forwardingDestination);
}
}
- const rawR2Key = await storeRawToR2(env, message.from, message.to, message.raw);
+ const rawR2Key = await storeRawToR2(env, message.from, message.to, raw);
const payload: InboundQueueMessage = {
from: message.from,
to: message.to,