@sayedhfatimi/convex-email 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +709 -2
  3. package/dist/adapters/index.d.ts +2 -0
  4. package/dist/adapters/index.d.ts.map +1 -0
  5. package/dist/adapters/index.js +7 -0
  6. package/dist/adapters/index.js.map +1 -0
  7. package/dist/adapters/registry.d.ts +9 -0
  8. package/dist/adapters/registry.d.ts.map +1 -0
  9. package/dist/adapters/registry.js +20 -0
  10. package/dist/adapters/registry.js.map +1 -0
  11. package/dist/adapters/resend/inbound.d.ts +5 -0
  12. package/dist/adapters/resend/inbound.d.ts.map +1 -0
  13. package/dist/adapters/resend/inbound.js +207 -0
  14. package/dist/adapters/resend/inbound.js.map +1 -0
  15. package/dist/adapters/resend/index.d.ts +4 -0
  16. package/dist/adapters/resend/index.d.ts.map +1 -0
  17. package/dist/adapters/resend/index.js +27 -0
  18. package/dist/adapters/resend/index.js.map +1 -0
  19. package/dist/adapters/resend/parse.d.ts +3 -0
  20. package/dist/adapters/resend/parse.d.ts.map +1 -0
  21. package/dist/adapters/resend/parse.js +94 -0
  22. package/dist/adapters/resend/parse.js.map +1 -0
  23. package/dist/adapters/resend/send.d.ts +15 -0
  24. package/dist/adapters/resend/send.d.ts.map +1 -0
  25. package/dist/adapters/resend/send.js +117 -0
  26. package/dist/adapters/resend/send.js.map +1 -0
  27. package/dist/adapters/resend/webhook.d.ts +6 -0
  28. package/dist/adapters/resend/webhook.d.ts.map +1 -0
  29. package/dist/adapters/resend/webhook.js +66 -0
  30. package/dist/adapters/resend/webhook.js.map +1 -0
  31. package/dist/adapters/ses/inbound.d.ts +3 -0
  32. package/dist/adapters/ses/inbound.d.ts.map +1 -0
  33. package/dist/adapters/ses/inbound.js +52 -0
  34. package/dist/adapters/ses/inbound.js.map +1 -0
  35. package/dist/adapters/ses/index.d.ts +4 -0
  36. package/dist/adapters/ses/index.d.ts.map +1 -0
  37. package/dist/adapters/ses/index.js +28 -0
  38. package/dist/adapters/ses/index.js.map +1 -0
  39. package/dist/adapters/ses/parse.d.ts +7 -0
  40. package/dist/adapters/ses/parse.d.ts.map +1 -0
  41. package/dist/adapters/ses/parse.js +209 -0
  42. package/dist/adapters/ses/parse.js.map +1 -0
  43. package/dist/adapters/ses/send.d.ts +10 -0
  44. package/dist/adapters/ses/send.d.ts.map +1 -0
  45. package/dist/adapters/ses/send.js +179 -0
  46. package/dist/adapters/ses/send.js.map +1 -0
  47. package/dist/adapters/ses/sigv4.d.ts +19 -0
  48. package/dist/adapters/ses/sigv4.d.ts.map +1 -0
  49. package/dist/adapters/ses/sigv4.js +50 -0
  50. package/dist/adapters/ses/sigv4.js.map +1 -0
  51. package/dist/adapters/ses/sns.d.ts +23 -0
  52. package/dist/adapters/ses/sns.d.ts.map +1 -0
  53. package/dist/adapters/ses/sns.js +281 -0
  54. package/dist/adapters/ses/sns.js.map +1 -0
  55. package/dist/adapters/types.d.ts +11 -0
  56. package/dist/adapters/types.d.ts.map +1 -0
  57. package/dist/adapters/types.js +2 -0
  58. package/dist/adapters/types.js.map +1 -0
  59. package/dist/client/index.d.ts +214 -0
  60. package/dist/client/index.d.ts.map +1 -0
  61. package/dist/client/index.js +304 -0
  62. package/dist/client/index.js.map +1 -0
  63. package/dist/component/_generated/api.d.ts +62 -0
  64. package/dist/component/_generated/api.d.ts.map +1 -0
  65. package/dist/component/_generated/api.js +31 -0
  66. package/dist/component/_generated/api.js.map +1 -0
  67. package/dist/component/_generated/component.d.ts +345 -0
  68. package/dist/component/_generated/component.d.ts.map +1 -0
  69. package/dist/component/_generated/component.js +11 -0
  70. package/dist/component/_generated/component.js.map +1 -0
  71. package/dist/component/_generated/dataModel.d.ts +46 -0
  72. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  73. package/dist/component/_generated/dataModel.js +11 -0
  74. package/dist/component/_generated/dataModel.js.map +1 -0
  75. package/dist/component/_generated/server.d.ts +133 -0
  76. package/dist/component/_generated/server.d.ts.map +1 -0
  77. package/dist/component/_generated/server.js +80 -0
  78. package/dist/component/_generated/server.js.map +1 -0
  79. package/dist/component/attachments.d.ts +21 -0
  80. package/dist/component/attachments.d.ts.map +1 -0
  81. package/dist/component/attachments.js +66 -0
  82. package/dist/component/attachments.js.map +1 -0
  83. package/dist/component/cleanup.d.ts +15 -0
  84. package/dist/component/cleanup.d.ts.map +1 -0
  85. package/dist/component/cleanup.js +152 -0
  86. package/dist/component/cleanup.js.map +1 -0
  87. package/dist/component/config.d.ts +34 -0
  88. package/dist/component/config.d.ts.map +1 -0
  89. package/dist/component/config.js +33 -0
  90. package/dist/component/config.js.map +1 -0
  91. package/dist/component/convex.config.d.ts +3 -0
  92. package/dist/component/convex.config.d.ts.map +1 -0
  93. package/dist/component/convex.config.js +8 -0
  94. package/dist/component/convex.config.js.map +1 -0
  95. package/dist/component/credentials.d.ts +19 -0
  96. package/dist/component/credentials.d.ts.map +1 -0
  97. package/dist/component/credentials.js +45 -0
  98. package/dist/component/credentials.js.map +1 -0
  99. package/dist/component/deliver.d.ts +58 -0
  100. package/dist/component/deliver.d.ts.map +1 -0
  101. package/dist/component/deliver.js +328 -0
  102. package/dist/component/deliver.js.map +1 -0
  103. package/dist/component/events.d.ts +15 -0
  104. package/dist/component/events.d.ts.map +1 -0
  105. package/dist/component/events.js +141 -0
  106. package/dist/component/events.js.map +1 -0
  107. package/dist/component/inbound.d.ts +354 -0
  108. package/dist/component/inbound.d.ts.map +1 -0
  109. package/dist/component/inbound.js +933 -0
  110. package/dist/component/inbound.js.map +1 -0
  111. package/dist/component/queries.d.ts +76 -0
  112. package/dist/component/queries.d.ts.map +1 -0
  113. package/dist/component/queries.js +175 -0
  114. package/dist/component/queries.js.map +1 -0
  115. package/dist/component/schema.d.ts +473 -0
  116. package/dist/component/schema.d.ts.map +1 -0
  117. package/dist/component/schema.js +185 -0
  118. package/dist/component/schema.js.map +1 -0
  119. package/dist/component/send.d.ts +112 -0
  120. package/dist/component/send.d.ts.map +1 -0
  121. package/dist/component/send.js +393 -0
  122. package/dist/component/send.js.map +1 -0
  123. package/dist/component/status.d.ts +2 -0
  124. package/dist/component/status.d.ts.map +1 -0
  125. package/dist/component/status.js +8 -0
  126. package/dist/component/status.js.map +1 -0
  127. package/dist/component/suppression.d.ts +36 -0
  128. package/dist/component/suppression.d.ts.map +1 -0
  129. package/dist/component/suppression.js +89 -0
  130. package/dist/component/suppression.js.map +1 -0
  131. package/dist/component/unsubscribe.d.ts +58 -0
  132. package/dist/component/unsubscribe.d.ts.map +1 -0
  133. package/dist/component/unsubscribe.js +129 -0
  134. package/dist/component/unsubscribe.js.map +1 -0
  135. package/dist/component/webhooks.d.ts +36 -0
  136. package/dist/component/webhooks.d.ts.map +1 -0
  137. package/dist/component/webhooks.js +71 -0
  138. package/dist/component/webhooks.js.map +1 -0
  139. package/dist/shared/address.d.ts +9 -0
  140. package/dist/shared/address.d.ts.map +1 -0
  141. package/dist/shared/address.js +76 -0
  142. package/dist/shared/address.js.map +1 -0
  143. package/dist/shared/authResults.d.ts +15 -0
  144. package/dist/shared/authResults.d.ts.map +1 -0
  145. package/dist/shared/authResults.js +86 -0
  146. package/dist/shared/authResults.js.map +1 -0
  147. package/dist/shared/htmlToText.d.ts +13 -0
  148. package/dist/shared/htmlToText.d.ts.map +1 -0
  149. package/dist/shared/htmlToText.js +221 -0
  150. package/dist/shared/htmlToText.js.map +1 -0
  151. package/dist/shared/mime.d.ts +4 -0
  152. package/dist/shared/mime.d.ts.map +1 -0
  153. package/dist/shared/mime.js +63 -0
  154. package/dist/shared/mime.js.map +1 -0
  155. package/dist/shared/readCapped.d.ts +7 -0
  156. package/dist/shared/readCapped.d.ts.map +1 -0
  157. package/dist/shared/readCapped.js +38 -0
  158. package/dist/shared/readCapped.js.map +1 -0
  159. package/dist/shared/sanitize.d.ts +10 -0
  160. package/dist/shared/sanitize.d.ts.map +1 -0
  161. package/dist/shared/sanitize.js +68 -0
  162. package/dist/shared/sanitize.js.map +1 -0
  163. package/dist/shared/threading.d.ts +6 -0
  164. package/dist/shared/threading.d.ts.map +1 -0
  165. package/dist/shared/threading.js +23 -0
  166. package/dist/shared/threading.js.map +1 -0
  167. package/dist/shared/types.d.ts +260 -0
  168. package/dist/shared/types.d.ts.map +1 -0
  169. package/dist/shared/types.js +2 -0
  170. package/dist/shared/types.js.map +1 -0
  171. package/dist/shared/unsubToken.d.ts +15 -0
  172. package/dist/shared/unsubToken.d.ts.map +1 -0
  173. package/dist/shared/unsubToken.js +83 -0
  174. package/dist/shared/unsubToken.js.map +1 -0
  175. package/dist/shared/validators.d.ts +760 -0
  176. package/dist/shared/validators.d.ts.map +1 -0
  177. package/dist/shared/validators.js +200 -0
  178. package/dist/shared/validators.js.map +1 -0
  179. package/package.json +88 -4
  180. package/src/adapters/index.ts +8 -0
  181. package/src/adapters/registry.ts +28 -0
  182. package/src/adapters/resend/inbound.ts +245 -0
  183. package/src/adapters/resend/index.ts +29 -0
  184. package/src/adapters/resend/parse.ts +118 -0
  185. package/src/adapters/resend/send.ts +125 -0
  186. package/src/adapters/resend/webhook.ts +77 -0
  187. package/src/adapters/ses/inbound.ts +63 -0
  188. package/src/adapters/ses/index.ts +30 -0
  189. package/src/adapters/ses/parse.ts +236 -0
  190. package/src/adapters/ses/send.ts +206 -0
  191. package/src/adapters/ses/sigv4.ts +56 -0
  192. package/src/adapters/ses/sns.ts +321 -0
  193. package/src/adapters/types.ts +27 -0
  194. package/src/client/index.ts +549 -0
  195. package/src/component/_generated/api.ts +78 -0
  196. package/src/component/_generated/component.ts +475 -0
  197. package/src/component/_generated/dataModel.ts +60 -0
  198. package/src/component/_generated/server.ts +169 -0
  199. package/src/component/attachments.ts +69 -0
  200. package/src/component/cleanup.ts +173 -0
  201. package/src/component/config.ts +52 -0
  202. package/src/component/convex.config.ts +9 -0
  203. package/src/component/credentials.ts +63 -0
  204. package/src/component/deliver.ts +380 -0
  205. package/src/component/events.ts +179 -0
  206. package/src/component/inbound.ts +1107 -0
  207. package/src/component/queries.ts +203 -0
  208. package/src/component/schema.ts +222 -0
  209. package/src/component/send.ts +467 -0
  210. package/src/component/status.ts +8 -0
  211. package/src/component/suppression.ts +114 -0
  212. package/src/component/unsubscribe.ts +154 -0
  213. package/src/component/webhooks.ts +84 -0
  214. package/src/shared/address.ts +75 -0
  215. package/src/shared/authResults.ts +94 -0
  216. package/src/shared/htmlToText.ts +218 -0
  217. package/src/shared/mime.ts +80 -0
  218. package/src/shared/readCapped.ts +39 -0
  219. package/src/shared/sanitize.ts +73 -0
  220. package/src/shared/threading.ts +26 -0
  221. package/src/shared/types.ts +254 -0
  222. package/src/shared/unsubToken.ts +95 -0
  223. package/src/shared/validators.ts +282 -0
  224. package/src/test.ts +25 -0
package/README.md CHANGED
@@ -1,3 +1,710 @@
1
- # Temporary Holding Version
1
+ # @sayedhfatimi/convex-email
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A provider-neutral email component for [Convex](https://convex.dev). One client class, `Email`, sends and receives mail through Resend or Amazon SES, stores every message and delivery event, and keeps suppressions, unsubscribes and threads in one place, so you can move from one provider to the other without losing any of it.
4
+
5
+ - Sending is queued: `mail.send` returns a message id at once and delivery runs in the background with retries.
6
+ - Credentials never enter the component. Your app supplies them from a callback, per use.
7
+ - Test mode is on by default: only addresses you allowlist are really sent to.
8
+ - Delivery events (sent, delivered, bounced, complained, ...) update the message and, for hard bounces and complaints, suppress the address.
9
+ - Inbound mail (Resend receiving, SES receipt rules, or raw MIME you hold) is parsed, cleaned, threaded and handed to your `onInbound` function.
10
+ - Optional tenants: one deployment can serve several customers, each with their own provider account.
11
+
12
+ Status: released (0.1.x) and tested live against Resend and Amazon SES. What was confirmed, and what is still open, is under [Verified live, and what is not yet](#verified-live-and-what-is-not-yet).
13
+
14
+ The component runs entirely in Convex's default runtime. Components cannot contain `"use node"` files, so HTML cleaning, SNS signature checks and SigV4 signing all use runtime-neutral libraries.
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ bun add @sayedhfatimi/convex-email
20
+ # or: npm install @sayedhfatimi/convex-email
21
+ ```
22
+
23
+ Requires `convex` `^1.51.1`. Mount the component in `convex/convex.config.ts`:
24
+
25
+ ```ts
26
+ import { defineApp } from "convex/server";
27
+ import email from "@sayedhfatimi/convex-email/convex.config.js";
28
+
29
+ const app = defineApp();
30
+ app.use(email);
31
+
32
+ export default app;
33
+ ```
34
+
35
+ ## What your app writes
36
+
37
+ The example app in [`example/convex`](example/convex) is the working version of the next two files (shown here slightly condensed), and every other sample in this README is copied from [`example/convex/readmeExamples.ts`](example/convex/readmeExamples.ts). Both are type-checked against the real API by `bun run check`.
38
+
39
+ ```ts
40
+ // convex/email.ts
41
+ import { v } from "convex/values";
42
+ import {
43
+ type CredentialPurpose,
44
+ Email,
45
+ type ProviderName,
46
+ type ResendCredentials,
47
+ type SesCredentials,
48
+ type UnsubscribeCredentials,
49
+ vCredentialPurpose,
50
+ vEventForApp,
51
+ vInboundForApp,
52
+ vProviderName,
53
+ } from "@sayedhfatimi/convex-email";
54
+ import { components, internal } from "./_generated/api";
55
+ import { internalAction, internalMutation } from "./_generated/server";
56
+
57
+ export const mail = new Email(components.email, {
58
+ providers: ["resend", "ses"], // every provider this deployment talks to
59
+ sendVia: "resend", // where new mail goes; flipping it is the cutover
60
+ credentials: internal.email.credentials,
61
+ onInbound: internal.email.route, // optional
62
+ onEvent: internal.email.onEvent, // optional
63
+ // Mail only really leaves for the allowlist until EMAIL_LIVE=true.
64
+ testMode: process.env.EMAIL_LIVE !== "true",
65
+ testAllowlist: ["me@example.com"],
66
+ resend: { ownDomains: ["example.com"] }, // Resend inbound only, see below
67
+ unsubscribe: { url: `${process.env.CONVEX_SITE_URL}/email/unsubscribe` },
68
+ });
69
+
70
+ /**
71
+ * The only place a secret is read. The component calls this for every send,
72
+ * inbound fetch, webhook verification and unsubscribe, and keeps nothing.
73
+ */
74
+ export const credentials = internalAction({
75
+ args: {
76
+ provider: v.union(vProviderName, v.null()),
77
+ tenant: v.union(v.string(), v.null()),
78
+ purpose: vCredentialPurpose,
79
+ },
80
+ handler: async (
81
+ _ctx,
82
+ args: {
83
+ provider: ProviderName | null;
84
+ tenant: string | null;
85
+ purpose: CredentialPurpose;
86
+ },
87
+ ): Promise<ResendCredentials | SesCredentials | UnsubscribeCredentials> => {
88
+ // Asked with `provider: null`: the secret belongs to no provider, so
89
+ // unsubscribe links keep working across a provider cutover.
90
+ if (args.purpose === "unsubscribe") {
91
+ return { unsubscribeSecret: process.env.EMAIL_UNSUBSCRIBE_SECRET! };
92
+ }
93
+ if (args.provider === "resend") {
94
+ return {
95
+ provider: "resend",
96
+ apiKey: process.env.RESEND_API_KEY!,
97
+ webhookSecret: process.env.RESEND_WEBHOOK_SECRET!,
98
+ };
99
+ }
100
+ if (args.provider === "ses") {
101
+ return {
102
+ provider: "ses",
103
+ region: process.env.AWS_REGION!,
104
+ accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
105
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
106
+ configurationSets: {
107
+ transactional: process.env.SES_CONFIGURATION_SET!,
108
+ },
109
+ trustedTopicArns: process.env.SES_TOPIC_ARNS!.split(","),
110
+ inboundBuckets: process.env.SES_INBOUND_BUCKETS!.split(","),
111
+ };
112
+ }
113
+ throw new Error("unknown provider");
114
+ },
115
+ });
116
+
117
+ export const route = internalMutation({
118
+ args: vInboundForApp,
119
+ handler: async (_ctx, message) => ({
120
+ handled: message.verdicts.dmarc === "pass",
121
+ }),
122
+ });
123
+
124
+ export const onEvent = internalMutation({
125
+ args: vEventForApp,
126
+ handler: async () => null,
127
+ });
128
+ ```
129
+
130
+ The `!` assertions keep the snippet short; the example app checks each variable and fails with its name when one is missing.
131
+
132
+ Create **one `Email` instance per component mount** and use it everywhere. Each call stores the options it was made with (provider list, handles, test mode, adapter options) in a single config row that background work reads; two instances with different options would overwrite each other, last writer wins. A message's unsubscribe settings are the exception: they are captured when it is sent.
133
+
134
+ Routes are mounted by your app, not by the component:
135
+
136
+ ```ts
137
+ // convex/http.ts
138
+ import { httpRouter } from "convex/server";
139
+ import { mail } from "./email";
140
+
141
+ const http = httpRouter();
142
+
143
+ // Each configured provider keeps its own route; both stay mounted in a cutover.
144
+ // On Resend mount ONE account-level route: Resend sends every event to every
145
+ // endpoint, so per-tenant Resend routes would store each inbound mail once per
146
+ // route.
147
+ http.route({
148
+ path: "/email/webhook/resend",
149
+ method: "POST",
150
+ handler: mail.webhookHandler("resend"),
151
+ });
152
+ http.route({
153
+ path: "/email/webhook/ses",
154
+ method: "POST",
155
+ handler: mail.webhookHandler("ses"),
156
+ });
157
+ // Tenants with their own provider accounts mount a tenant path segment.
158
+ http.route({
159
+ pathPrefix: "/email/webhook/ses/",
160
+ method: "POST",
161
+ handler: mail.webhookHandler("ses", {
162
+ tenantPathPrefix: "/email/webhook/ses/",
163
+ }),
164
+ });
165
+
166
+ // The page your app serves at this URL receives `t` and POSTs it back (see
167
+ // Unsubscribe). Without `redirectTo` the built-in confirm page is shown.
168
+ http.route({
169
+ path: "/email/unsubscribe",
170
+ method: "GET",
171
+ handler: mail.unsubscribeHandler({
172
+ redirectTo: "https://app.example.com/unsubscribed",
173
+ }),
174
+ });
175
+ http.route({
176
+ path: "/email/unsubscribe",
177
+ method: "POST",
178
+ handler: mail.unsubscribeHandler(),
179
+ });
180
+
181
+ export default http;
182
+ ```
183
+
184
+ The webhook URLs are on your deployment's HTTP actions domain (`https://<deployment>.convex.site/email/webhook/resend`).
185
+
186
+ ## Sending
187
+
188
+ `mail.send(ctx, input)` works from a mutation or an action and returns the message id. It validates, writes the message row and the bodies, and queues delivery; it does not wait for the provider.
189
+
190
+ ```ts
191
+ export const sendTicketReply = mutation({
192
+ args: {
193
+ to: v.string(),
194
+ ticketId: v.string(),
195
+ replyId: v.string(),
196
+ inReplyTo: v.string(),
197
+ },
198
+ handler: async (ctx, { to, ticketId, replyId, inReplyTo }): Promise<string> =>
199
+ await mail.send(ctx, {
200
+ from: "Support <support@example.com>",
201
+ to,
202
+ subject: "Re: your request",
203
+ text: "Thanks, we are on it.",
204
+ inReplyTo,
205
+ tags: { ticket: ticketId },
206
+ // One key per reply: a key per ticket would swallow every later reply.
207
+ idempotencyKey: `ticket-reply-${replyId}`,
208
+ }),
209
+ });
210
+ ```
211
+
212
+ Fields: `from`, `to`, `cc`, `bcc`, `replyTo` (a string or an array), `subject`, `html` and/or `text` (at least one), `attachments`, `inReplyTo`, `category`, `tenant`, `stream`, `tags`, `headers`, `idempotencyKey`.
213
+
214
+ - `inReplyTo` is a component message id or an RFC `Message-ID`. The component sets `In-Reply-To` and `References` and puts the message in the parent's thread.
215
+ - `stream` is `"transactional"` (default) or `"bulk"`. Each has its own queue, so a newsletter cannot delay a sign-in email. A bulk send can use a second SES configuration set (`configurationSets.bulk`).
216
+ - `idempotencyKey` is per tenant: a second `send` with the same key returns the first message's id instead of sending again.
217
+ - `tags` come back on `onEvent` and, for replies, on `parent.tags` in `onInbound`. Keys match `^[A-Za-z][A-Za-z0-9_-]{0,63}$`, values match `^[A-Za-z0-9_-]{1,256}$`, at most 50 tags, and the `cx_` prefix is reserved.
218
+ - `headers` are extra headers. You cannot set structural or threading headers (`From`, `To`, `Cc`, `Bcc`, `Sender`, `Reply-To`, `Subject`, `Date`, `Return-Path`, `MIME-Version`, `Message-ID`, `In-Reply-To`, `References`, `List-Unsubscribe`, `List-Unsubscribe-Post`, anything `Content-*`), and each name may appear once (case-insensitive). At most 50 headers, each value up to 998 characters with no control characters. SESv2 accepts at most 15 custom headers: more than that is a permanent error from SES.
219
+ - At most 100 recipients across `to`, `cc` and `bcc`. Addresses are lower-cased and de-duplicated. Recipients are sent as bare addresses (display names are not kept) in 0.1.0; the `from` display name is kept (on SES a non-ASCII one is RFC 2047 encoded).
220
+ - When `unsubscribe` is configured, a message with a `category` must have exactly one recipient across `to`, `cc` and `bcc`: the unsubscribe link in it names that address.
221
+ - The raw size limit is 10 MiB on both adapters (bodies plus attachments). The providers allow about 30 MiB raw (40 MB after base64), but a send holds the whole message in memory in Convex's default runtime, so the component stays well below that; the live probes measure the real ceiling.
222
+
223
+ Sending from an action works the same way:
224
+
225
+ ```ts
226
+ export const sendFromAction = action({
227
+ args: { to: v.string() },
228
+ handler: async (ctx, { to }): Promise<string> =>
229
+ await mail.send(ctx, {
230
+ from: "Example <hello@example.com>",
231
+ to,
232
+ subject: "Sent from an action",
233
+ text: "Hello.",
234
+ }),
235
+ });
236
+ ```
237
+
238
+ ### Attachments
239
+
240
+ Store the file first, then pass its id. An attachment can be linked to one message only.
241
+
242
+ ```ts
243
+ export const sendWithAttachment = mutation({
244
+ args: { to: v.string(), bytes: v.bytes() },
245
+ handler: async (ctx, { to, bytes }): Promise<string> => {
246
+ const invoice = await mail.storeAttachment(ctx, {
247
+ bytes,
248
+ filename: "invoice.pdf",
249
+ contentType: "application/pdf",
250
+ });
251
+ return await mail.send(ctx, {
252
+ from: "Billing <billing@example.com>",
253
+ to,
254
+ subject: "Your invoice",
255
+ text: "Attached.",
256
+ attachments: [invoice],
257
+ });
258
+ },
259
+ });
260
+ ```
261
+
262
+ For a large file, have the browser upload to a one-time URL instead of passing bytes through a mutation:
263
+
264
+ ```ts
265
+ export const startUpload = mutation({
266
+ args: {},
267
+ handler: async (ctx): Promise<string> => await mail.attachmentUploadUrl(ctx),
268
+ });
269
+
270
+ export const finishUpload = mutation({
271
+ args: {
272
+ storageId: v.string(),
273
+ filename: v.string(),
274
+ contentType: v.string(),
275
+ },
276
+ handler: async (ctx, args): Promise<string> =>
277
+ await mail.registerUpload(ctx, args),
278
+ });
279
+ ```
280
+
281
+ `storeAttachment` and `registerUpload` also take `contentId` and `disposition: "inline"` for images referenced from the HTML (`cid:`). Files that are stored but never attached are removed by `cleanup`.
282
+
283
+ ### Statuses
284
+
285
+ A message's `status` is one of `queued`, `test`, `suppressed`, `sending`, `sent`, `delivery_delayed`, `delivered`, `bounced`, `complained`, `failed`, `rejected` (and `received` for inbound mail). It only moves forward, so events that arrive out of order cannot undo a later state. `mail.status(ctx, id)` returns it; `mail.get(ctx, id)` returns the message with its attachments, events and short-lived URLs for the stored bodies (`null` once `cleanup` has removed them).
286
+
287
+ Delivery to the provider is retried when the failure is transient (8 attempts, backing off from 5 s and doubling: about ten minutes in all), and recorded as `failed` with an error text when it is not or when the attempts run out. The error text never contains a credential and is cut to 1000 characters. The transactional queue runs 4 sends at a time, the bulk queue 2.
288
+
289
+ `mail.retrySend(ctx, messageId)` queues a `failed` message again (status back to `queued`, error cleared, on its own stream's queue). It re-runs the suppression and unsubscribe checks first, so a recipient who bounced, complained or unsubscribed since is dropped into `suppressedRecipients`; if no `To` recipient is left the message becomes `suppressed` and is not queued. It returns the resulting status (`queued` or `suppressed`). It throws for any other status, and for a failure the provider reported after accepting the message (send that one anew). When an attempt ended without an answer from the provider (a network error or a timeout), the message is marked `deliveryAmbiguous` (readable from `get`): the provider may already have delivered it. `retrySend` then refuses unless you pass `{ force: true }`. Resend drops a resend of the same message within its idempotency window (the key is the component message id); SES has no idempotency key, so a forced retry on SES can deliver twice.
290
+
291
+ ```ts
292
+ export const retryFailedSend = mutation({
293
+ args: { id: v.string(), force: v.optional(v.boolean()) },
294
+ handler: async (ctx, { id, force }): Promise<void> => {
295
+ await mail.retrySend(ctx, id, { force });
296
+ },
297
+ });
298
+ ```
299
+
300
+ Delivery is at-least-once in one narrow window: if the process dies between the provider accepting a message and the component recording it, the retry sends again. Resend drops the duplicate through the `Idempotency-Key` header (the component message id); SES has no idempotency key, so on SES that window can produce a duplicate.
301
+
302
+ ## Credentials and the security model
303
+
304
+ The `credentials` callback is an `internalAction` of yours. The component calls it with `{ provider, tenant, purpose }` every time it needs a secret (`send`, `fetchInbound`, `verifyWebhook`, `unsubscribe`), uses the result in memory, and discards it. No API key, AWS secret, webhook secret or unsubscribe secret is written to a table, a log line or an error message. What the component stores is a function handle for your callback (a reference, not a secret).
305
+
306
+ For one set of credentials from environment variables, see `email.ts` above. For per-tenant secrets, look them up by tenant:
307
+
308
+ ```ts
309
+ type TenantSecrets = {
310
+ resendApiKey: string;
311
+ resendWebhookSecret: string;
312
+ unsubscribeSecret: string;
313
+ };
314
+
315
+ /** Replace the body with a lookup in your own (encrypted) table. */
316
+ export const tenantSecrets = internalQuery({
317
+ args: { tenant: v.string() },
318
+ handler: async (_ctx, { tenant }): Promise<TenantSecrets | null> => {
319
+ const all: Record<string, TenantSecrets> = JSON.parse(
320
+ process.env.TENANT_SECRETS ?? "{}",
321
+ );
322
+ return all[tenant] ?? null;
323
+ },
324
+ });
325
+
326
+ export const tenantCredentials = internalAction({
327
+ args: {
328
+ provider: v.union(vProviderName, v.null()),
329
+ tenant: v.union(v.string(), v.null()),
330
+ purpose: vCredentialPurpose,
331
+ },
332
+ handler: async (
333
+ ctx,
334
+ args: {
335
+ provider: ProviderName | null;
336
+ tenant: string | null;
337
+ purpose: CredentialPurpose;
338
+ },
339
+ ): Promise<ResendCredentials | SesCredentials | UnsubscribeCredentials> => {
340
+ if (args.tenant === null) throw new Error("a tenant is required");
341
+ const secrets: TenantSecrets | null = await ctx.runQuery(
342
+ internal.readmeExamples.tenantSecrets,
343
+ { tenant: args.tenant },
344
+ );
345
+ if (!secrets) throw new Error("unknown tenant");
346
+ if (args.purpose === "unsubscribe") {
347
+ return { unsubscribeSecret: secrets.unsubscribeSecret };
348
+ }
349
+ if (args.provider === "resend") {
350
+ return {
351
+ provider: "resend",
352
+ apiKey: secrets.resendApiKey,
353
+ webhookSecret: secrets.resendWebhookSecret,
354
+ };
355
+ }
356
+ throw new Error("unsupported provider");
357
+ },
358
+ });
359
+ ```
360
+
361
+ Throw for a tenant you do not know: a message whose credentials cannot be fetched is recorded as `failed`, and a webhook for it gets a 500 and is not stored (the provider retries it).
362
+
363
+ **Your app authorises reads.** The component has no notion of users. `status`, `get`, `inboundBody` and `attachmentUrl` take bare ids, so anything you expose to a client must first check that the id belongs to the caller (and tenant) in your own tables:
364
+
365
+ ```ts
366
+ export const myMessageStatus = query({
367
+ args: { id: v.string() },
368
+ handler: async (ctx, { id }): Promise<string | null> => {
369
+ const identity = await ctx.auth.getUserIdentity();
370
+ if (!identity) throw new Error("not signed in");
371
+ // Check here that `id` belongs to this user (your own table) before
372
+ // asking the component about it.
373
+ return await mail.status(ctx, id);
374
+ },
375
+ });
376
+ ```
377
+
378
+ Other rules the component keeps for you: it never reads `process.env`, never reads `ctx.auth`, and defines no HTTP routes of its own.
379
+
380
+ ## Test mode
381
+
382
+ `testMode` defaults to `true`. In test mode, a message is only sent when every remaining recipient (to, cc and bcc) is in `testAllowlist`; otherwise it is stored with status `test` and nothing leaves. Set `testMode: false` (the example uses `EMAIL_LIVE=true`) when you are ready for real recipients. Suppressed and unsubscribed recipients are dropped before the test-mode check.
383
+
384
+ ## Tenants
385
+
386
+ `tenant` is optional everywhere. The component keeps suppressions, unsubscribes, Message-ID lookups and threads inside a tenant, and passes the tenant to your `credentials` callback.
387
+
388
+ - A single-tenant app never passes one.
389
+ - An app with one tenant per deployment sets `tenant` in the `Email` options: it is the default for every call that does not pass its own.
390
+ - A multi-tenant app passes `tenant` on each call (`send`, `storeAttachment`, `suppressions.*`, `unsubscribes.*`, `listUnhandled`, `receiveRaw`).
391
+ - On SES the tenant is also sent as the SES `TenantName`. On Resend it is kept by the component only and never sent to the provider.
392
+
393
+ Webhooks are verified with the tenant's own credentials, so the tenant has to come from the URL, not the payload. Mount the route with a `tenantPathPrefix` (the route's own `pathPrefix`); exactly one path segment after it is the tenant, matching `[A-Za-z0-9._~-]{1,128}`, and anything else is a 400. Events and inbound mail are scoped to the tenant whose credentials verified the webhook.
394
+
395
+ On a shared provider account mounted with one account-level route (no route tenant and no default `tenant`; the right set-up for Resend), inbound mail arrives with no tenant. When it answers one of your messages and its `From` is one of that message's recipients, it takes that message's tenant and the `onInbound` message carries `tenantAdopted: true`. A stranger quoting the same Message-ID gets neither the tenant nor a `parent`. Known limit: a redelivered, tenant-adopted inbound message that has no Message-ID can be stored twice (rare: Resend inbound always carries one).
396
+
397
+ Two consequences to plan for:
398
+
399
+ - An app that sets a default tenant but also sends for other tenants through one shared provider account needs per-tenant routes on SES (one SNS subscription per tenant route): the plain route belongs to the default tenant, so events for other tenants' messages arriving there are stored as unmatched (orphan) events. On a shared Resend account per-tenant routes do not work (Resend sends every event to every endpoint): leave the default tenant unset and mount one account-level route.
400
+ - Messages stored without a tenant become unmatched once a default tenant is configured: events no longer find them. Pick the default before you send.
401
+
402
+ ## Delivery events
403
+
404
+ Each webhook is verified, parsed into normalized events and appended to the message's event log: `sent`, `delivered`, `delivery_delayed`, `bounced` (with `bounceType`: `hard`, `soft` or `undetermined`), `complained`, `failed`, `rejected`. Duplicates (providers redeliver) are ignored. An event for a message this component did not send, for example from another product on a shared Resend account, is stored as an orphan and otherwise ignored. Orphan events accumulate: `cleanup` does not prune them yet.
405
+
406
+ `onEvent` is called through a queue for each event that matched a message (not for orphans), so a slow handler never blocks the webhook:
407
+
408
+ ```ts
409
+ export const onEvent = internalMutation({
410
+ args: vEventForApp, // { messageId, type, bounceType?, at, tags }
411
+ handler: async (): Promise<null> => null,
412
+ });
413
+ ```
414
+
415
+ ### Suppression
416
+
417
+ A hard bounce or a complaint adds a suppression for the addresses the message went to. Soft and undetermined bounces do not. A suppressed address is dropped from later sends (listed in the message's `suppressedRecipients`); if every recipient is dropped, or every `to` recipient is (no message goes out without a `To`), the message is `suppressed`. Addresses are lower-cased and trimmed, never plus-stripped.
418
+
419
+ ```ts
420
+ export const suppressed = query({
421
+ args: { paginationOpts: paginationOptsValidator },
422
+ handler: async (ctx, { paginationOpts }) =>
423
+ await mail.suppressions.list(ctx, { paginationOpts }),
424
+ });
425
+
426
+ export const unsuppress = mutation({
427
+ args: { address: v.string() },
428
+ handler: async (ctx, { address }): Promise<void> => {
429
+ await mail.suppressions.remove(ctx, { address });
430
+ },
431
+ });
432
+ ```
433
+
434
+ `mail.suppressions.add` adds one by hand.
435
+
436
+ ### Unsubscribe
437
+
438
+ Send with a `category` and, if you configured `unsubscribe: { url, mailto? }`, the message carries `List-Unsubscribe` (your URL with a signed token `t`, plus a `mailto:` when set) and `List-Unsubscribe-Post: List-Unsubscribe=One-Click`. The token is signed with the `unsubscribeSecret` from your credentials callback, which is asked with `{ provider: null, tenant, purpose: "unsubscribe" }` both when signing and when checking a link, so links survive a provider cutover. The token names the tenant, address and category. The URL and `mailto` are those configured when the message was sent. A bulk send with a category and no `unsubscribe` option is rejected; on the transactional stream the header is simply left off.
439
+
440
+ ```ts
441
+ export const sendNewsletter = mutation({
442
+ args: { to: v.string() },
443
+ handler: async (ctx, { to }): Promise<string> =>
444
+ await mail.send(ctx, {
445
+ from: "News <news@example.com>",
446
+ to,
447
+ subject: "This month",
448
+ html: "<p>News.</p>",
449
+ stream: "bulk",
450
+ category: "newsletter",
451
+ }),
452
+ });
453
+ ```
454
+
455
+ How `unsubscribeHandler` behaves:
456
+
457
+ - **POST** is the RFC 8058 one-click path used by mail clients. It records the unsubscribe and answers `200 ok`, or `400` for a bad link. The token is read from the query string or from a form field `t`.
458
+ - **GET** never records anything (link scanners fetch GETs). With `redirectTo` it redirects to your page with `t`, `category` and `ok` (`ok=1`, or `ok=0` for a bad link) appended; your page should send `Referrer-Policy: no-referrer`, show a confirm button and POST `t` back to the unsubscribe route. Without `redirectTo` it serves a built-in page with one confirm button that posts the token back.
459
+
460
+ Read and change a person's choices from your own preferences screen:
461
+
462
+ ```ts
463
+ export const preferences = query({
464
+ args: { address: v.string() },
465
+ handler: async (ctx, { address }) =>
466
+ await mail.unsubscribes.list(ctx, { address }),
467
+ });
468
+
469
+ export const resubscribe = mutation({
470
+ args: { address: v.string() },
471
+ handler: async (ctx, { address }): Promise<void> => {
472
+ await mail.unsubscribes.set(ctx, {
473
+ address,
474
+ category: "newsletter",
475
+ unsubscribed: false,
476
+ });
477
+ },
478
+ });
479
+ ```
480
+
481
+ ## Inbound mail
482
+
483
+ Mail arrives from a provider webhook (Resend receiving, an SES receipt rule) or from `mail.receiveRaw`. Each one gets a stored row. A queued job fetches the full message, parses the MIME, cleans the HTML, stores bodies and attachments in file storage, resolves the thread, and calls your `onInbound` function with a normalized message. You return `{ handled: boolean, note?: string }`. If the function throws or returns `handled: false`, the message is kept as `unhandled`.
484
+
485
+ ```ts
486
+ export const routeInbound = internalMutation({
487
+ args: vInboundForApp,
488
+ handler: async (
489
+ _ctx,
490
+ message,
491
+ ): Promise<{ handled: boolean; note?: string }> => {
492
+ if (message.verdicts.dmarc !== "pass") {
493
+ return { handled: false, note: "DMARC did not pass" };
494
+ }
495
+ // `parent.tags` are the tags this app set when it sent the original. A
496
+ // reply from someone who was not a recipient only quotes our Message-ID,
497
+ // so check `senderWasRecipient` before trusting them.
498
+ const ticket = message.parent?.senderWasRecipient
499
+ ? message.parent.tags.ticket
500
+ : undefined;
501
+ if (ticket === undefined) {
502
+ return { handled: false, note: "not a reply to a ticket" };
503
+ }
504
+ return { handled: true };
505
+ },
506
+ });
507
+ ```
508
+
509
+ What the handler receives (`InboundForApp`): `messageId`, `tenant`, `provider` (`"resend"`, `"ses"` or `"raw"`), `from`, `to`, `cc`, `subject`, `text`, `textFromHtml`, cleaned `html`, `bodyByReference`, `hasRemoteImages`, `attachments` (`id`, `filename`, `contentType`, `size`), `verdicts` (`spf`, `dkim`, `dmarc`), `threadId`, `parent`, `truncated`, `tenantAdopted`, and the stored `headers`. The `note` you return is kept on the inbound row (`appNote` in `listUnhandled`), handled or not.
510
+
511
+ - **Bodies.** Text plus HTML over 256 KiB are not passed inline (`bodyByReference: true`); read them in an action with `mail.inboundBody(ctx, messageId)`. Attachment bytes: `mail.attachmentUrl(ctx, attachmentId)` returns a short-lived URL.
512
+ - **Text.** `text` is present whenever the message had any body. When the sender sent no text part (absent, empty or only whitespace) but did send HTML (common for automated senders), the component derives `text` from the HTML (read before cleaning, so `<title>`, `<noscript>`, `<template>`, `<svg>`, `hidden` and `display:none` content such as preheaders is left out) and sets `textFromHtml: true` on the `onInbound` message and on the `get` view. Blocks and `<br>` become line breaks, list items get `- `, a link reads `text [url]` (just the text when it equals the URL), entities are decoded, and images, styles, scripts, zero-width padding and tracking pixels are dropped. A real text part is kept verbatim and `textFromHtml` is absent. A message with no readable content in either part has no `text`. Derived text is cut at 1 MiB (and the message marked `truncated`), and the HTML it is read from at 2 MiB.
513
+ - **HTML** is cleaned with an allow-list. Remote images are kept but flagged (`hasRemoteImages`, and each one carries `data-remote-image`) so you can block or allow them; block them by default. Inline raster `data:` images (png, jpeg, gif, webp; base64 only) are kept and not flagged, since Resend's Receiving API may inline `cid:` images as data URIs; every other `data:` source is dropped. Bodies and attachments served by short-lived URLs come from the deployment's storage origin with the sender's content type: never open them on a sensitive origin (one that holds your session).
514
+ - **Parent.** When the message answers one of ours, `parent` has the outbound message id and its `tags`. `senderWasRecipient` is `true` only when the inbound `From` was one of that message's recipients; check it before trusting `parent.tags` (ticket ids, say), because anyone can quote our Message-ID.
515
+ - **Adopted tenant.** `tenantAdopted: true` (also readable from `get`) means the message arrived with no tenant (an account-level route) and took `tenant` from the outbound message it answers, because its `From` was one of that message's recipients. `From` is not authenticated by itself: check `verdicts` (DMARC) before acting on an adopted tenant.
516
+ - **Message-IDs** are stored in `<…>` form whatever the provider hands over, so replies thread to your outbound mail on every adapter.
517
+ - **Verdicts.** SPF, DKIM and DMARC come from the provider where it gives them and those always win: SES always does, and Resend does too, from the `authentication` block of its Receiving API (read when the message is fetched). So `trustedAuthServIds` is not needed for Resend. Its receiving host signs `Authentication-Results` as `receive.forge.rmta.net` (observed 2026-12-03), should you ever want the header instead. Otherwise they are read from an `Authentication-Results` header, but only when `trustedAuthServIds` lists the id of the host that added it. Set that list only for a receiving service that adds its own header and strips forged ones carrying its id; only the topmost header is considered. With no match, no verdicts are recorded.
518
+ - **Duplicates.** A second notification for the same provider id does nothing. Inbound mail with the same Message-ID, sender and content as a stored message is a duplicate; a Message-ID reused by a different message is stored separately and flagged.
519
+ - **Limits.** Sender-controlled fields are bounded so a row always fits Convex's 1 MiB document limit: subject 2000 bytes, 200 headers (8 KiB per value, 64 KiB in total), 500 addresses per list, 100 attachments, filenames 255 bytes. Anything cut marks the stored message `truncated`. The flag is `truncated` on the `onInbound` message (present only when `true`) and on the `get` view. A message over 10 MiB fails permanently on SES. On Resend, an attachment over the limit is skipped and the message is marked `truncated`.
520
+ - **Failures.** A provider fetch that fails is retried after 30 s, 2 min and 10 min, then the row becomes `failed`. Nothing is dropped silently: failed and unhandled rows stay listable.
521
+
522
+ ```ts
523
+ /** Bodies over 256 KiB arrive `bodyByReference`: read them in an action. */
524
+ export const readBody = internalAction({
525
+ args: { id: v.string() },
526
+ handler: async (ctx, { id }): Promise<{ text?: string; html?: string }> =>
527
+ await mail.inboundBody(ctx, id),
528
+ });
529
+
530
+ /** A support screen: unhandled and failed inbound mail, and a retry. */
531
+ export const unhandled = query({
532
+ args: {},
533
+ handler: async (ctx) => await mail.listUnhandled(ctx, { limit: 50 }),
534
+ });
535
+
536
+ export const retry = action({
537
+ args: { id: v.string() },
538
+ handler: async (ctx, { id }) => await mail.retryInbound(ctx, id),
539
+ });
540
+ ```
541
+
542
+ `retryInbound` re-runs a `failed` message from the start, and calls `onInbound` again for an `unhandled` one. For any other state it does nothing and returns `{ acted: false, state }`. The id to pass is the inbound row's `id` from `listUnhandled`.
543
+
544
+ If you already hold the raw message (for example your own mail router), hand it in; it runs the same pipeline:
545
+
546
+ ```ts
547
+ export const receiveFromRouter = action({
548
+ args: { mime: v.bytes() },
549
+ handler: async (ctx, { mime }): Promise<string> =>
550
+ await mail.receiveRaw(ctx, {
551
+ mime,
552
+ source: "console-router",
553
+ // Omit `verdicts` to fall back to a trusted Authentication-Results header.
554
+ verdicts: { spf: "pass", dkim: "pass", dmarc: "pass" },
555
+ }),
556
+ });
557
+ ```
558
+
559
+ Verdicts you pass are recorded with `source` as their origin, never as the provider's, and are authoritative: no header is read, even when you pass `{}`. The `keepRawMime` option applies to `receiveRaw` only: the raw bytes are stored for it and deleted after parsing unless `keepRawMime` is `true`. Provider-delivered mail is never kept raw by the component.
560
+
561
+ ## Resend set-up
562
+
563
+ 1. Add and verify your sending domain in Resend (the DNS records it shows), and create an API key.
564
+ 2. Add a webhook pointing at `https://<deployment>.convex.site/email/webhook/resend` (or the per-tenant route). Subscribe to the email events (`email.sent`, `email.delivered`, `email.delivery_delayed`, `email.bounced`, `email.complained`, `email.failed`) and, for inbound, `email.received`. Resend signs with Svix: its signing secret (`whsec_...`) is the `webhookSecret` you return from `credentials`.
565
+ 3. Mount one account-level Resend route (no `tenantPathPrefix`) per Resend account and leave the default `tenant` unset if the account is shared by tenants: Resend sends every event to every endpoint, so per-tenant routes would store each inbound mail once per route. Inbound replies take their tenant from the message they answer (see Tenants).
566
+ 4. For inbound, enable receiving on a domain (its MX record) and set `resend: { ownDomains: ["example.com"] }` (entries are trimmed, lower-cased and lose a leading `@`). Resend delivers every domain on the account to every webhook, so the adapter keeps only mail with a recipient whose domain exactly matches one of `ownDomains` (subdomains are not matched; list them). The `Email` constructor throws if `"resend"` is a provider, `onInbound` is set and `ownDomains` is missing or empty, because every Resend inbound message would otherwise be ignored.
567
+ 5. Return `{ provider: "resend", apiKey, webhookSecret }` from your callback.
568
+
569
+ Resend dedupes sends through the `Idempotency-Key` header, which the component sets to the message id. Tags starting `cx_` are never sent to Resend.
570
+
571
+ ## Amazon SES set-up
572
+
573
+ 1. **Identity.** Verify the domain (or address) you send from in SES, in the region you will use, and move the account out of the sandbox. While the account is still in the sandbox, SES only delivers to verified identities, and it checks the sender's IAM permission against the **recipient's** identity as well. So add each verified recipient's identity ARN (for example `arn:aws:ses:<region>:<account>:identity/you@example.org`) to the `ses:SendEmail` resources in step 5, or every send to it fails with `AccessDeniedException`. SES's mailbox simulator addresses are exempt.
574
+ 2. **Configuration sets, one per stream.** Create a configuration set for the transactional stream (and a second one for bulk if you want separate reputation and metrics). Add an event destination to each that publishes to an SNS topic, with the event types `Send`, `Delivery`, `DeliveryDelay`, `Bounce`, `Complaint`, `Reject` and `Rendering Failure`. Return them as `configurationSets: { transactional, bulk? }`; a bulk send uses the transactional set when no bulk one is given.
575
+ 3. **SNS to the webhook.** Subscribe each topic over HTTPS to `https://<deployment>.convex.site/email/webhook/ses` (or the per-tenant route). The component confirms the subscription itself. It verifies every SNS message signature (the signing certificate is fetched only from an `sns.<region>.amazonaws.com` host) and refuses topics that are not listed: put every topic ARN, including the inbound one, in `trustedTopicArns`. A failed verification is a 401; a certificate that cannot be fetched (network error, timeout, non-2xx) is a 500, so SNS delivers the message again.
576
+ 4. **Inbound (optional).** Verify the receiving domain's MX record, create an S3 bucket, and add a receipt rule with an S3 action that writes to the bucket and notifies an SNS topic (the notification must carry the bucket and object key, so set the topic on the S3 action). Subscribe the topic to the same webhook. List the bucket in `inboundBuckets`: the adapter will only read buckets named there, and with none listed it refuses all inbound fetches. SES receiving is only available in some regions.
577
+ 5. **IAM.** The credentials you return need to send and, for inbound, to read the bucket. A starting policy:
578
+
579
+ ```json
580
+ {
581
+ "Version": "2012-10-17",
582
+ "Statement": [
583
+ {
584
+ "Effect": "Allow",
585
+ "Action": "ses:SendEmail",
586
+ "Resource": [
587
+ "arn:aws:ses:eu-west-1:111122223333:identity/example.com",
588
+ "arn:aws:ses:eu-west-1:111122223333:configuration-set/transactional",
589
+ "arn:aws:ses:eu-west-1:111122223333:configuration-set/bulk"
590
+ ],
591
+ "Condition": {
592
+ "StringLike": { "ses:FromAddress": "*@example.com" }
593
+ }
594
+ },
595
+ {
596
+ "Effect": "Allow",
597
+ "Action": "s3:GetObject",
598
+ "Resource": "arn:aws:s3:::example-inbound-mail/*"
599
+ }
600
+ ]
601
+ }
602
+ ```
603
+
604
+ The `ses:FromAddress` condition stops the key from being used to send as any other address. Adjust regions, account id, names and the sender pattern; if you use SES tenants, also grant what AWS requires for them. Use a dedicated IAM user with just this policy.
605
+
606
+ Return `{ provider: "ses", region, accessKeyId, secretAccessKey, sessionToken?, configurationSets, trustedTopicArns, inboundBuckets }` from your callback.
607
+
608
+ SES chooses the `Message-ID` itself, so the component sends none. It records the id SES puts in the delivered header, `<MessageId@<region>.amazonses.com>` (`<MessageId@email.amazonses.com>` in us-east-1). SES's events carry only the bare `MessageId`, without `@`, which is never allowed to replace it. Replies quote the full form in `In-Reply-To`, so they thread. The tenant, when there is one, is sent as the SES `TenantName`.
609
+
610
+ ## Capabilities
611
+
612
+ | | Resend | Amazon SES |
613
+ | ------------------------------ | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
614
+ | Inbound | yes (Receiving API) | yes (receipt rule to S3 + SNS) |
615
+ | Provider-side tenants | no (tenant kept by the component only) | yes (`TenantName`) |
616
+ | Provider-side list management | no | available in SES; unused, because the component sends its own `List-Unsubscribe` headers on both |
617
+ | Max message / attachment (raw) | 10 MiB / 10 MiB | 10 MiB / 10 MiB |
618
+ | Idempotency on send | yes (`Idempotency-Key`) | no |
619
+ | Custom headers per message | 50 (the component's limit) | 15 (SESv2); more is a permanent error |
620
+ | Events | sent, delivered, delivery_delayed, bounced, complained, failed | sent, delivered, delivery_delayed, bounced, complained, rejected, failed |
621
+ | Webhook verification | Svix signature, 5 min tolerance | SNS signature + trusted topics |
622
+
623
+ A `send` that is over the size limit of the provider in `sendVia` throws at the call. A tenant on Resend is not an error: it is honoured by the component (records, suppression, unsubscribes, credentials) and never sent to Resend, so provider-side isolation of tenants needs SES.
624
+
625
+ ## Moving from Resend to SES
626
+
627
+ One component instance can hold both providers, so moving keeps every suppression, unsubscribe, thread and live unsubscribe link, and can be rolled back.
628
+
629
+ 1. Keep `providers: ["resend", "ses"]`, set up SES as above, and keep both webhook routes mounted (Resend still reports events for mail it already sent, and inbound keeps arriving there until the MX record moves).
630
+ 2. Make your `credentials` callback return SES credentials for `provider: "ses"`.
631
+ 3. Flip `sendVia`:
632
+
633
+ ```ts
634
+ /** The same options as the main example, with SES as the sending provider. */
635
+ export const mailOnSes = new Email(components.email, {
636
+ providers: ["resend", "ses"],
637
+ sendVia: "ses",
638
+ credentials: internal.email.credentials,
639
+ onInbound: internal.email.route,
640
+ testMode: process.env.EMAIL_LIVE !== "true",
641
+ testAllowlist: ["me@example.com"],
642
+ resend: { ownDomains: ["example.com"] },
643
+ });
644
+ ```
645
+
646
+ Every message records the provider that sent or received it, and an old message's events are still matched to it. Flip `sendVia` back to roll back. A configuration where `sendVia` is not in `providers` throws on construction.
647
+
648
+ ## Housekeeping
649
+
650
+ `cleanup({ olderThanMs })` deletes stored bodies, attachment rows and files, and the kept raw MIME of handled inbound mail, for messages older than the cut-off. It keeps message rows and events, so history and threading survive. It never touches `queued` or `sending` messages, or inbound mail that is unhandled or failed. It is global (not per tenant) and bounded per call: when it returns `more: true`, call it again. A duplicate inbound row never purges the message it points at; only the row that stored that message does. Orphan events are not pruned yet.
651
+
652
+ ```ts
653
+ /** Runs `cleanup` again while it reports `more`. */
654
+ export const cleanupAll = internalAction({
655
+ args: {},
656
+ handler: async (ctx): Promise<number> => {
657
+ let removed = 0;
658
+ for (;;) {
659
+ const batch: { removed: number; more: boolean } = await ctx.runMutation(
660
+ internal.email.cleanup,
661
+ {},
662
+ );
663
+ removed += batch.removed;
664
+ if (!batch.more) return removed;
665
+ }
666
+ },
667
+ });
668
+
669
+ /** Export this as the default from `convex/crons.ts`. */
670
+ export const exampleCrons = () => {
671
+ const crons = cronJobs();
672
+ crons.interval("clean email", { hours: 24 }, internal.email.cleanup);
673
+ return crons;
674
+ };
675
+ ```
676
+
677
+ where `internal.email.cleanup` is the `internalMutation` in the example app that calls `mail.cleanup(ctx, { olderThanMs: 90 * 24 * 60 * 60 * 1000 })`.
678
+
679
+ ## Verified live, and what is not yet
680
+
681
+ Checked against the real services on 2026-12-03, on Resend and on SES in eu-north-1 (in the sandbox):
682
+
683
+ - **Resend** replaces the component's `Message-ID` with its own. The component records the real one from the events, and replies thread.
684
+ - **SES** delivers the header `<MessageId@eu-north-1.amazonses.com>`, which the component records, and replies thread.
685
+ - **Resend's Receiving API and its `email.received` webhook** match the adapter. The test fixtures are captured real payloads, with personal data replaced.
686
+ - **Bounces and complaints** (both providers' simulators) suppress the address, and a late `delivered` event does not undo a complaint.
687
+ - **Inbound on SES** works end to end (MX, receipt rule, S3, SNS, the component), with SES's own SPF/DKIM/DMARC verdicts.
688
+ - **Switching providers** (`sendVia` from SES back to Resend) keeps suppressions.
689
+
690
+ Not yet verified live:
691
+
692
+ - The us-east-1 SES header host (`email.amazonses.com`), which is covered by tests only.
693
+ - A send for a tenant on SES (SES `TenantName`).
694
+ - A late Resend event arriving after switching to SES.
695
+ - How large a message the default runtime can send and receive. The 10 MiB cap is deliberately conservative until then.
696
+
697
+ ## Development
698
+
699
+ - `bun install`
700
+ - `bun run check` runs Biome, `tsc --noEmit` for `src` and `example/convex`, and the vitest suite (`vitest run --typecheck`).
701
+ - `bun run build` emits `dist`.
702
+ - `bun run build:codegen` regenerates `src/component/_generated` and `example/convex/_generated`, then builds. It needs a Convex deployment (`convex codegen` has none to talk to otherwise), so run it locally against a local deployment after you change a component function. The generated files are committed, and CI relies on them instead of running codegen.
703
+ - Tests use `vi.useFakeTimers()`, register the component with `register(t)` from `@sayedhfatimi/convex-email/test`, and drain queued jobs with `await t.finishAllScheduledFunctions(vi.runAllTimers)`.
704
+ - TypeScript 7.0.2, Biome for lint and format, bun for everything. npm is used only by the release workflow to publish.
705
+ - Releases are cut from `v*` tags. The workflow checks the tag against `package.json`, requires the tagged commit to be on `main`, and runs the checks. It then packs the tested build. A separate job, which installs and runs nothing from the project, stages that tarball on npm through trusted publishing (OIDC, no npm token, bound to the `npm` environment that only `v*` tags may use), with provenance. A staged version goes public only when the maintainer approves it with 2FA (`npm stage approve`). A version with a `-` (for example `0.2.0-rc.1`) is staged under the `next` dist-tag, and a version already on npm is skipped.
706
+ - Release checklist: run `bun run build:codegen` before tagging, and commit any change it makes to the `_generated` files (a test fails when a public function is missing from `src/component/_generated/component.ts`).
707
+
708
+ ## License
709
+
710
+ Apache-2.0