Skip to content

Email for professionals and teams

Merge main into feat/pwa-web-push

Hieu Nguyen (Jack)c8795ae39eb4
diff --cc docs/deployment.md
index bad9956,d1349fa..c8a1276
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@@ -8,37 -8,42 +8,50 @@@ Set up Mailflare in three steps
1. **Deploy the app:** use the Deploy to Cloudflare button, set the app name to `mailflare`, and provide the required `CF_TOKEN`.
2. **Complete setup:** open the deployed app and follow `/setup` to check the installation and create the first admin account.
- 3. **Connect your domain:** add a domain managed by the same Cloudflare account. Mailflare configures email routing and, when available and selected, email sending before helping you create the first mailbox.
+ 3. **Connect your domain:** add a domain managed by the same Cloudflare account and choose which service receives its mail. Mailflare configures email routing and, when available and selected, email sending before helping you create the first mailbox. Resend and Amazon SES are alternatives to Cloudflare for receiving and sending; see [Sending and receiving providers](providers.md).
- The Worker name must remain `mailflare`. Before starting, create the required `CF_TOKEN` with **Zone Read**, **DNS Edit**, **Email Routing Edit**, and **Email Routing Rules Write** permissions for every domain you plan to connect. DNS Edit lets the confirmed setup flow replace conflicting MX records. Add **Email Sending Edit** when Mailflare should send email; it is optional for receive-only domains.
- ## Step 1: Deploy mailflare
+ ## Step 1: Setup CF_TOKEN
+ To configure your `CF_TOKEN` (which is a scoped Cloudflare API Token with specific permissions), follow the below steps.
- [![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/hieunc229/mailflare)
+ 1. In your Cloudflare account, navigate to `Manage Account` → `Account API Tokens` and create a new token.
+ 2. At the top of the Policy window, select `Specified Domains` for all domains that you plan to connect
+ 1. Then configure these permissions
+ 1. DNS & Zones > DNS > Select `Edit` Access
+ 1. This allows the confirmed setup flow to replace conflicting MX records
+ 2. DNS & Zones > Zone > Select `Read` Access
+ 3. DNS & Zones → Zone Settings → Select `Edit` Access
+ 4. Email & Messaging > Email Routing Rules > Select `Edit` Access
+ 3. If mailflare will send emails: Add another policy and select `Entire Account`, and configure these permissions:
+ 1. Email & Messaging > Email Sending > Select `Edit` Access
+ 4. After your token is setup, go to `Compute` → `Email Service` → `Email Sending`
+ 1. You will need to purchase a paid workers plan if you don't already have one
+ 2. Select On-board domain and follow the prompts
+ 3. After this is done, and after you have setup Mailflare, on the Admin > domains page, when you expand the domain you can then configure DKIM and DMARC records
- 1. Click **Deploy to Cloudflare** above and sign in to Cloudflare if prompted.
- 2. Choose the Cloudflare account that owns the domain you want to use.
- 3. Set the app name to exactly `mailflare`. Do not rename it.
- 4. Add `CF_TOKEN` when Cloudflare asks for the app's runtime variables or secrets.
- 5. Start the deployment and wait for Cloudflare to finish provisioning and deploying the Worker.
+ Paste only the token secret into the `CF_TOKEN` field in step 2. Do not include the word `Bearer` and do not use the token ID. The token must belong to the same Cloudflare account as the domains you connect.
- ### Required configuration
+ ## Step 2: Deploy mailflare
- Mailflare requires this runtime value:
+ 1. Click **Deploy to Cloudflare** and sign in to Cloudflare if prompted.
- - `CF_TOKEN` — a scoped Cloudflare API token with **Zone Read**, **DNS Edit**, **Email Routing Edit**, and **Email Routing Rules Write** access for the domains you will connect. Add **Email Sending Edit** to enable outbound mail. This is separate from the token Cloudflare uses to deploy the app.
+ [![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/hieunc229/mailflare)
+
+ 2. Choose the Cloudflare account that owns the domain you want to use.
+ 3. Set the app name to exactly `mailflare`. Do not rename it.
+ 4. Add `CF_TOKEN` when Cloudflare asks for the app's runtime variables or secrets. This is different from the CF_TOKEN that Cloudflare uses to deploy the app.
+ 5. Start the deployment and wait for Cloudflare to finish provisioning and deploying the Worker.
- Paste only the token secret into `CF_TOKEN`. Do not include the word `Bearer` and do not use the token ID. The token must belong to the same Cloudflare account as the domains you connect.
+### Optional Web Push configuration
+
+To enable background new-mail notifications, run `npm run push:keys` once and
+store `VAPID_PRIVATE_KEY` as a Worker secret. Configure `VAPID_PUBLIC_KEY` and
+`VAPID_SUBJECT` as Worker variables; the subject must be a `mailto:` URI or the
+public HTTPS URL of the installation. The same VAPID key pair should be kept
+across deployments so existing browser subscriptions remain valid.
+
- ## Step 2: Complete mailflare setup
+ ## Step 3: Complete mailflare setup
1. Open the URL of the deployed `mailflare` Worker.
2. Go to `/setup` if Mailflare does not take you there automatically.
diff --cc docs/self-hosting.md
index ac4b660,5b97d1e..e39bae5
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@@ -92,11 -86,13 +101,16 @@@ and the DNS page shows what to set by h
| `SMTP_URL` | unset | Outbound relay |
| `SMTP_TLS_REJECT_UNAUTHORIZED` | `true` | Trust self-signed relay certificates when `false` |
| `CF_ACCOUNT_ID`, `CF_TOKEN` | unset | Cloudflare Email Sending, and zone management if the token allows |
+ | `RESEND_API_KEY` | unset | Resend key, used when none is saved in the app |
+ | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION` | unset | Amazon SES credentials, used when none are saved in the app |
| `INBOUND_WEBHOOK_SECRET` | unset | Enables `/api/inbound` for the relay Worker |
| `TURNSTILE_SECRET_KEY` | unset | Bot protection on login and reset forms (`NEXT_PUBLIC_TURNSTILE_SITE_KEY` at build time) |
+| `VAPID_PUBLIC_KEY` | unset | Public Web Push application-server key |
+| `VAPID_PRIVATE_KEY` | unset | Secret Web Push application-server key |
+| `VAPID_SUBJECT` | unset | Web Push contact URI (`mailto:` or HTTPS) |
+ | `AI_BASE_URL` | unset | OpenAI-compatible model API base URL for the assistant |
+ | `AI_API_KEY` | unset | Server-only key for that model API |
+ | `AI_MODEL` | `gpt-4o-mini` | Model ID supported by the configured API |
## Operations
diff --cc drizzle/migrations/0054_add_push_subscriptions.sql
index 7924906,0000000..7924906
mode 100644,000000..100644
--- a/drizzle/migrations/0054_add_push_subscriptions.sql
+++ b/drizzle/migrations/0054_add_push_subscriptions.sql
diff --cc drizzle/migrations/meta/_journal.json
index d872e63,8ea5a5a..aa06754
--- a/drizzle/migrations/meta/_journal.json
+++ b/drizzle/migrations/meta/_journal.json
@@@ -225,6 -225,104 +225,111 @@@
"when": 1788850800003,
"tag": "0031_add_password_reset_and_mfa",
"breakpoints": true
+ },
+ {
+ "idx": 32,
+ "version": "6",
+ "when": 1788850800004,
+ "tag": "0032_add_agentic_mail",
+ "breakpoints": true
+ },
+ {
+ "idx": 33,
+ "version": "6",
+ "when": 1788850800005,
+ "tag": "0033_add_agent_provider_settings",
+ "breakpoints": true
+ },
+ {
+ "idx": 34,
+ "version": "6",
+ "when": 1788850800006,
+ "tag": "0034_add_agent_enabled",
+ "breakpoints": true
+ },
+ {
+ "idx": 35,
+ "version": "6",
+ "when": 1788850800007,
+ "tag": "0035_add_mailbox_agent_model",
+ "breakpoints": true
+ },
+ {
+ "idx": 36,
+ "version": "6",
+ "when": 1788850800008,
+ "tag": "0036_add_agent_ai_usage",
+ "breakpoints": true
+ },
+ {
+ "idx": 37,
+ "version": "6",
+ "when": 1788850800009,
+ "tag": "0037_generalize_ai_usage",
+ "breakpoints": true
+ },
+ {
+ "idx": 38,
+ "version": "6",
+ "when": 1788850800010,
+ "tag": "0038_scope_standard_api_keys",
+ "breakpoints": true
+ },
+ {
+ "idx": 39,
+ "version": "6",
+ "when": 1788850800011,
+ "tag": "0039_add_backup_table_groups",
+ "breakpoints": true
+ },
+ {
+ "idx": 40,
+ "version": "6",
+ "when": 1788850800012,
+ "tag": "0040_add_agent_draft_schedule",
+ "breakpoints": true
+ },
+ {
+ "idx": 41,
+ "version": "6",
+ "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
+ },
+ {
+ "idx": 43,
+ "version": "6",
+ "when": 1788850800015,
+ "tag": "0051_add_outbound_provider",
+ "breakpoints": true
+ },
+ {
+ "idx": 44,
+ "version": "6",
+ "when": 1788850800016,
+ "tag": "0052_add_receiving_provider",
+ "breakpoints": true
+ },
+ {
+ "idx": 45,
+ "version": "6",
+ "when": 1788850800017,
+ "tag": "0053_add_trash_retention",
+ "breakpoints": true
++ },
++ {
++ "idx": 46,
++ "version": "6",
++ "when": 1788850800018,
++ "tag": "0054_add_push_subscriptions",
++ "breakpoints": true
}
]
}
diff --cc package.json
index 8610d48,c4c5547..8b0381e
--- a/package.json
+++ b/package.json
@@@ -1,20 -1,19 +1,20 @@@
{
"name": "mailflare",
- "version": "0.2.1",
+ "version": "0.5.0",
"private": true,
"scripts": {
- "dev": "npm run db:bundle && next dev",
- "build": "npm run db:bundle && next build",
- "build:next": "npm run db:bundle && next build",
- "start": "next start",
+ "dev": "npm run db:bundle && vite dev --port 3000",
+ "build": "npm run db:bundle && vite build",
+ "build:next": "npm run db:bundle && MAILFLARE_RUNTIME=node next build",
+ "start": "vite preview --port 3000",
"lint": "eslint .",
- "deploy": "npm run db:bundle && opennextjs-cloudflare build && npm run deploy:worker",
- "deploy:worker": "OPEN_NEXT_DEPLOY=true wrangler deploy",
+ "deploy": "npm run build && npm run deploy:worker",
+ "deploy:worker": "wrangler deploy",
"deploy:local": "npm run deploy",
- "upload": "npm run db:bundle && opennextjs-cloudflare build && OPEN_NEXT_DEPLOY=true wrangler versions upload",
- "preview": "npm run db:bundle && opennextjs-cloudflare build && opennextjs-cloudflare preview",
+ "upload": "npm run build && wrangler versions upload",
+ "preview": "npm run build && vite preview --port 3000",
"cf-typegen": "wrangler types --env-interface CloudflareEnv ./cloudflare-env.d.ts",
+ "push:keys": "node scripts/generate-vapid-keys.mjs",
"db:bundle": "node scripts/generate-migration-bundle.mjs",
"db:generate": "drizzle-kit generate",
"db:migrate:local": "wrangler d1 migrations apply DB --local",
diff --cc server/runtime/env.ts
index 7b66714,8f0bae6..98587b6
--- a/server/runtime/env.ts
+++ b/server/runtime/env.ts
@@@ -61,10 -67,8 +67,11 @@@ export function createNodeRuntime(): No
MAILFLARE_RUNTIME: "node",
APP_URL: optional("APP_URL")?.replace(/\/$/, ""),
INBOUND_WEBHOOK_SECRET: optional("INBOUND_WEBHOOK_SECRET"),
+ VAPID_PUBLIC_KEY: optional("VAPID_PUBLIC_KEY"),
+ VAPID_PRIVATE_KEY: optional("VAPID_PRIVATE_KEY"),
+ VAPID_SUBJECT: optional("VAPID_SUBJECT"),
} as unknown as CloudflareEnv;
+ realtime.bindEnv(env);
return {
env,
diff --cc src/app/(settings)/settings/inbox/page.tsx
index 7573f3a,2e0ad3d..58b96a9
--- a/src/app/(settings)/settings/inbox/page.tsx
+++ b/src/app/(settings)/settings/inbox/page.tsx
@@@ -2,18 -6,61 +6,65 @@@ import { InboxReadingLayoutSettings } f
import { InboxShortcutsSettings } from "@/components/settings/inbox-shortcuts-settings";
import { MailboxAutoReplyForm } from "@/components/settings/mailbox-auto-reply-form";
import { SpamFilterSettings } from "@/components/settings/spam-filter-settings";
+ import { TrashRetentionSettings } from "@/components/settings/trash-retention-settings";
+import { PushNotificationSettings } from "@/components/settings/push-notification-settings";
+ import { BrowserNotificationSettings } from "@/components/settings/browser-notification-settings";
- export default function SettingsInboxPage() {
+ export default async function SettingsInboxPage() {
+ const t = await getServerTranslator();
return (
<div className="space-y-8 py-4">
<section className="space-y-4">
<div>
- <h2 className="text-xl font-semibold text-neutral-900">Notifications</h2>
- <p className="mt-1 text-sm text-neutral-500">Choose how Mailflare alerts you about new messages.</p>
+ <h2 className="text-xl font-semibold text-neutral-900">{t("settingsPage.inbox.experience")}</h2>
+ <p className="mt-1 text-sm text-neutral-500">{t("settingsPage.inbox.experienceDescription")}</p>
</div>
- <div className="rounded-3xl bg-white p-6">
- <PushNotificationSettings />
+ <div className="divide-y divide-neutral-100 rounded-3xl bg-white p-6">
+ <div className="py-6 first:pt-0 last:pb-0">
+ <div className="mb-4">
+ <h3 className="text-base font-semibold text-neutral-900">{t("settingsPage.inbox.appearance")}</h3>
+ <p className="mt-1 text-sm text-neutral-500">{t("settingsPage.inbox.appearanceDescription")}</p>
+ </div>
+ <AppearanceSettings />
+ </div>
+ <div className="py-6 first:pt-0 last:pb-0">
+ <div className="mb-4">
+ <h3 className="text-base font-semibold text-neutral-900">{t("settingsPage.inbox.readingLayout")}</h3>
+ <p className="mt-1 text-sm text-neutral-500">{t("settingsPage.inbox.readingLayoutDescription")}</p>
+ </div>
+ <InboxReadingLayoutSettings />
+ </div>
+ <div className="py-6 first:pt-0 last:pb-0">
+ <div className="mb-4">
+ <h3 className="text-base font-semibold text-neutral-900">{t("settingsPage.inbox.threading")}</h3>
+ <p className="mt-1 text-sm text-neutral-500">{t("settingsPage.inbox.threadingDescription")}</p>
+ </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">{t("settingsPage.inbox.addresses")}</h3>
+ <p className="mt-1 text-sm text-neutral-500">{t("settingsPage.inbox.addressesDescription")}</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">{t("settingsPage.inbox.shortcuts")}</h3>
+ <p className="mt-1 text-sm text-neutral-500">{t("settingsPage.inbox.shortcutsDescription")}</p>
+ </div>
+ <InboxShortcutsSettings />
+ </div>
+ <div className="py-6 first:pt-0 last:pb-0">
+ <div className="mb-4">
+ <h3 className="text-base font-semibold text-neutral-900">{t("settingsPage.inbox.notifications")}</h3>
+ <p className="mt-1 text-sm text-neutral-500">{t("settingsPage.inbox.notificationsDescription")}</p>
+ </div>
+ <BrowserNotificationSettings />
++ <div className="mt-4">
++ <PushNotificationSettings />
++ </div>
+ </div>
</div>
</section>
<section className="space-y-4">
diff --cc src/components/providers.tsx
index ca30a0d,106701b..8029a02
--- a/src/components/providers.tsx
+++ b/src/components/providers.tsx
@@@ -5,7 -5,7 +5,8 @@@ import { useEffect, useState } from "re
import { clearMailboxClientState } from "@/components/mailbox-provider-utils";
import { BrandingProvider } from "@/components/branding-provider";
import { NewMessagePopup } from "@/components/new-message-popup";
+import { PwaServiceWorker } from "@/components/pwa-service-worker";
+ import { ThemeSync } from "@/components/theme-sync";
import { useMessagePolling } from "@/hooks/use-message-polling";
import { clearMessageClientState } from "@/hooks/utils";
import { clearMessageDetailCache } from "@/lib/messages/detail-cache";
@@@ -43,8 -45,8 +46,9 @@@ export function Providers({ children }
return (
<QueryClientProvider client={client}>
<BrandingProvider>
+ <PwaServiceWorker />
{children}
+ <ThemeSync />
{realtime.notification && (
<NewMessagePopup
notification={realtime.notification}
diff --cc src/hooks/message-realtime-utils.ts
index 77b68bc,93178b9..26470e4
--- a/src/hooks/message-realtime-utils.ts
+++ b/src/hooks/message-realtime-utils.ts
@@@ -47,16 -60,19 +61,20 @@@ export async function showBrowserNewMes
) {
return;
}
+ if (await hasActivePushSubscription().catch(() => false)) return;
- const notification = new Notification(event.subject || "New email", {
- body: `From ${event.fromName ?? event.from}`,
- icon: "/icon-96.png",
- tag: event.messageId,
- });
- notification.onclick = () => {
- window.focus();
- window.location.assign(`/inbox/${event.messageId}`);
- notification.close();
- };
+ try {
+ const notification = new Notification(event.subject || "New email", {
+ body: `From ${event.fromName ?? event.from}`,
+ icon: "/icon-96.png",
+ tag: event.messageId,
+ });
+ notification.onclick = () => {
+ window.focus();
+ window.location.assign(`/inbox/${event.messageId}`);
+ notification.close();
+ };
+ } catch {
+ // The in-app new message popup still handles this email.
+ }
}
diff --cc src/hooks/use-message-polling.ts
index b93fa6d,893fbab..e418fed
--- a/src/hooks/use-message-polling.ts
+++ b/src/hooks/use-message-polling.ts
@@@ -43,10 -49,52 +49,52 @@@ export function useMessagePolling(): Me
function startFallbackRefresh() {
if (fallbackTimer) return;
- fallbackTimer = window.setInterval(
- dispatchMessagesChanged,
- REALTIME_FALLBACK_INTERVAL_MS,
- );
+ fallbackTimer = window.setInterval(() => {
+ if (!connected && document.visibilityState === "visible") dispatchMessagesChanged();
+ }, REALTIME_FALLBACK_INTERVAL_MS);
+ }
+
+ function setConnected(value: boolean) {
+ connected = value;
+ if (value) {
+ if (fallbackTimer) window.clearInterval(fallbackTimer);
+ fallbackTimer = null;
+ } else {
+ startFallbackRefresh();
+ }
+ if (leader) channel?.postMessage({ type: "status", connected: value } satisfies RealtimeChannelMessage);
+ }
+
+ function handleNotification(payload: string, fromSocket: boolean) {
+ try {
+ const parsed = JSON.parse(payload) as { type?: string; revision?: string; changed?: boolean; draftId?: string; mailboxId?: string };
+ if (parsed.type === "revision" && typeof parsed.revision === "string") {
+ revision = parsed.revision;
+ if (parsed.changed) {
+ dispatchMessagesChanged();
+ if (fromSocket) channel?.postMessage({ type: "refresh" } satisfies RealtimeChannelMessage);
+ }
+ return;
+ }
+ if (parsed.type === "agent_draft" && parsed.draftId && parsed.mailboxId) {
+ window.dispatchEvent(new CustomEvent("mailflare:agent-draft", { detail: parsed }));
+ dispatchMessagesChanged();
+ if (fromSocket) channel?.postMessage({ type: "notification", payload } satisfies RealtimeChannelMessage);
+ return;
+ }
+ } catch { return; }
+ const event = parseNewMessageEvent(payload);
+ if (!event) return;
+ dispatchMessagesChanged();
+ setNotification(event);
+ if (fromSocket) {
- showBrowserNewMessageNotification(event);
++ void showBrowserNewMessageNotification(event);
+ channel?.postMessage({ type: "notification", payload } satisfies RealtimeChannelMessage);
+ }
+ }
+
+ function sendHeartbeat() {
+ if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: "ping", revision }));
}
function scheduleReconnect() {
diff --cc src/lib/realtime/utils.ts
index 23994f8,34e8712..307fe7a
--- a/src/lib/realtime/utils.ts
+++ b/src/lib/realtime/utils.ts
@@@ -2,8 -2,7 +2,8 @@@ import { eq } from "drizzle-orm"
import { getDb } from "@/db";
import { domains, mailboxAccess, mailboxes } from "@/db/schema";
import { isTeamMailboxSharingEnabled } from "@/lib/mailboxes/access-utils";
- import type { NewMessageNotification } from "./types";
+ import type { NewMessageNotification, AgentDraftNotification } from "./types";
+import { sendPushNotifications } from "@/lib/push/server";
export function getSessionTokenFromRequest(request: Request): string | undefined {
const cookie = request.headers.get("Cookie");
@@@ -52,10 -51,12 +52,12 @@@ export async function getMailboxNotific
export async function notifyUsersOfNewMessage(
env: CloudflareEnv,
userIds: string[],
- payload: NewMessageNotification,
+ payload: NewMessageNotification | AgentDraftNotification,
): Promise<void> {
+ // Next dev uses a bindings-only proxy; realtime delivery runs in worker.ts.
+ if (!env.REALTIME) return;
- await Promise.allSettled(
- userIds.map((userId) => {
+ await Promise.allSettled([
+ ...userIds.map((userId) => {
const hub = env.REALTIME.getByName(userId);
return hub.fetch("https://mailflare-realtime/notify", {
method: "POST",
@@@ -63,6 -64,5 +65,6 @@@
body: JSON.stringify(payload),
});
}),
- sendPushNotifications(env, userIds, payload),
- );
++ ...(payload.type === "agent_draft" ? [] : [sendPushNotifications(env, userIds, payload)]),
+ ]);
}