An app sends mail through one SMTP server: Protobase’s own mail (password reset, emailed sign-in codes, invitations, staff sign-in notices and mentions in comments) and the emails the app defines itself. Each is rendered to HTML with a plain-text part beside it.
Configuration
Section titled “Configuration”| Variable | |
|---|---|
PROTOBASE_SMTP_URL |
The SMTP server, credential included: smtp://user:password@host:587 (STARTTLS required) or smtps://user:password@host:465 (TLS from the start). |
PROTOBASE_MAIL_FROM |
The sender, a plain address such as [email protected]. The client greets the server with its domain; a ?name= on the URL overrides that. |
PROTOBASE_APP_NAME |
Optional: the app’s name, such as Shop, which mail clients show as the sender’s name (Shop <[email protected]>). It overrides the config’s name. Without either the sender has no name. |
Set both or neither. One without the other, a URL that is not smtp:// or smtps://, or a sender that is not a plain address stops the app at startup. Without them mail is off: password reset and emailed codes are not offered, a job’s mail is undefined, and sending an app’s email rejects.
protobase dev and protobase serve read them from the environment or the nearest .env; a host passes them like DATABASE_URL. In development, a mail catcher such as Mailpit shows what the app sends without delivering it:
docker run -d -p 8025:8025 -p 1025:1025 axllent/mailpit # its inbox is http://localhost:8025
PROTOBASE_SMTP_URL=smtp://localhost:1025?requireTLS=falseOver smtp:// the client always upgrades the connection with STARTTLS before it logs in or sends anything, so nobody between the app and the server reads the server’s password or the mail, such as a sign-in code or a reset link. A server that does not offer STARTTLS, or an answer from which someone on the way removed it, fails the send, with the code ETLS when the server refuses the upgrade. ?requireTLS=false on the URL is the only way to send in plaintext, for a server that has no TLS, such as the mail catcher above or a server on the same host. smtps:// uses TLS from the start.
A project that delivers its mail another way exports a mailer, { send({ to, subject, text, html, headers }) }, resolving to { messageId } when it knows the message’s Message-ID and {} when not, as the default of auth/mailer.ts: sign-in and the jobs (mail in their context) both send with it. auth: { mailer: false } turns sign-in’s mail off whatever the environment says. A host that runs jobs itself passes a mailer to startJobs. A template’s send takes one too, see Templates.
When the server does not answer
Section titled “When the server does not answer”A send through PROTOBASE_SMTP_URL gets 30 seconds in all: looking up the server, connecting to each of its addresses, its greeting, TLS, the login and the message. One that has not finished by then rejects with a MailServerTimeoutError (exported by @protobase/server) whose code is MAIL_SERVER_TIMEOUT, as when a firewall drops the mail port’s packets or the server never greets; it is not retried. Options on the URL, such as ?connectionTimeout=, cannot lift the limit. A server that answers and refuses keeps its own error code, such as EAUTH for a refused login or EENVELOPE for a refused sender.
Protobase’s own mail
Section titled “Protobase’s own mail”The auth emails (sign-in, two-factor and sign-up codes, the note to an address that asked to sign up while it has an account, password reset, invitations and staff sign-in notices) and the email to someone a comment mentions are email templates: a heading, the message, one code or button, and a footer naming the app.
- They come in English and Dutch. An auth email is in the app’s
localewhen the app sets one, else in the language of the browser that asked for it, such as the one that asked for a sign-in code, else in English. The mention email is in the app’slocale, else in English: it is sent by a job, after the request. - They name the app by its
name, and link it on the origin the request came to: the footer links its home page, and the note to an address that has an account links its sign-in page. - The plain-text part has each code on a line of its own and each link in full. A date, such as when an invitation’s link stops working, is written in the email’s language, in UTC:
October 15, 2026 at 12:00 PM UTC,15 oktober 2026 om 12:00 UTC. - React Email and the templates are loaded when the first auth email is sent, so an app that sends none never loads them and the server starts as fast without them.
Templates
Section titled “Templates”An email of the app’s own is a template: defineTemplate, with its data typed, its text in each language it is sent in, and its body written in mail blocks, as a typed layout is. The body is built once, as the config loads, into a static tree: data.name is the placeholder {{name}}, <Show when> and <Switch> choose by the data, and an ArrayField repeats a list of it. Export the template from config/index.ts, so the workflow step Send email lists it.
/** @jsxImportSource @protobase/layout */import { Button, Show, Text, Trans, translations } from '@protobase/layout'import { defineTemplate } from '@protobase/server'import { z } from 'zod'import en from './contact-reply.en.json'import nl from './contact-reply.nl.json'
export const contactReply = defineTemplate({ name: 'contact-reply', texts: translations({ en, nl }), schema: z.object({ name: z.string(), topic: z.enum(['sales', 'support']), days: z.number(), id: z.string() }), subject: ({ data }) => <Trans i18nKey="subject" values={{ name: data.name }} />, body: ({ data, app }) => ( <> <Text as="h1"><Trans i18nKey="greeting" values={{ name: data.name }} /></Text> <Text><Trans i18nKey="thanks" values={{ days: data.days }} /></Text> <Show when={data.topic.eq('sales')}> <Text><Trans i18nKey="sales" components={{ b: <Text as="strong" /> }} /></Text> </Show> <Button href={`${app.url}/contact/${data.id}`}><Trans i18nKey="cta" /></Button> </> ),}){ "subject": "We hebben je bericht ontvangen, {name}", "greeting": "Hoi {name},", "thanks": "{days, plural, one {We antwoorden binnen # werkdag.} other {We antwoorden binnen # werkdagen.}}", "sales": "Een collega van sales <b>belt je</b>.", "cta": "Bekijk je bericht"}defineTemplate option |
|
|---|---|
name |
Names the template, in errors and in the step’s list: a lowercase letter, then lowercase letters, digits and dashes. Each template of the app has its own. |
texts |
Its texts in each language it is sent in, translations({ en, nl }) of ICU messages, which its <Trans> elements show, as the app’s own texts are. Without it, the template is in one language, as written. |
subject |
The subject line: text, or a function of { data, app } that gives text or a <Trans>. |
preview |
Optional: the line inboxes show after the subject, as subject is written. |
schema |
Optional: a Standard Schema, such as a zod 4 schema, or Valibot’s with toStandardJsonSchema, which checks the data before each send and types it. |
headers |
Optional: more header fields, or a function of { data, app } that gives them, each one line. |
body |
A function of { data, app } that gives the mail’s blocks. app.name and app.url are the app the mail comes from. |
The body takes the mail blocks: Text (a paragraph, as="h1" to h4 for a heading, strong, em or span in a line), Trans, Link with an href, Button with an href, Image, Divider, Box, Row and Column, Show, Switch and Match, ArrayField with RecordsIterator, and Field. Any other block, such as a Table, fails as the config loads, as does a <Trans> key the texts lack.
The template that comes back has two methods, both typed by the data:
render(data, { locale, app })gives{ subject, html, text, headers, locale }without sending anything: for a test, or to look at the result.send(to, data, { locale, mailer, app, attachments })renders and sends it, throughmailerwhen given (a job’smail), otherwise throughPROTOBASE_SMTP_URL, and gives what it rendered. It rejects when mail is off or the server refuses the message.
A send is in the language of its texts closest to locale, by its tag (nl-BE) or its language (nl), else the app’s locale when the texts have it, else English, else the first; locale says which it was. With a schema, data the schema refuses rejects with TemplateDataError, naming each path, before anything is sent. The data’s JSON Schema, which the step draws its pins from, is the schema’s own, or without one each path the template reads, such as name and a list items with its title.
Emails in React
Section titled “Emails in React”An email can also be defineEmail: a name, a subject, and a React component whose props are the email’s data, for a layout the mail blocks cannot draw. The components of React Email render the tables and inline styles email clients need. @protobase/server brings React’s renderer; the project adds the components, and React for its JSX, which a project with a UI has already:
bun add react-email reactbun add -d @types/reactimport { defineEmail } from '@protobase/server'import { Body, Button, Container, Head, Heading, Html, Preview, Text } from 'react-email'
export type RepairReady = { customer: string; bike: string; number: string; url: string }
// The email's data is the component's props: `send` and `render` take exactly these.const RepairReadyEmail = ({ customer, bike, number, url }: RepairReady) => ( <Html lang="en"> <Head /> <Preview>Your {bike} is ready for pickup</Preview> <Body style={{ backgroundColor: '#f4f4f5', fontFamily: 'Helvetica, Arial, sans-serif' }}> <Container style={{ backgroundColor: '#ffffff', padding: '24px', maxWidth: '480px' }}> <Heading as="h1">Ready for pickup</Heading> <Text>Hi {customer}, your {bike} is ready. Bring repair number {number} when you come by.</Text> <Button href={url} style={{ backgroundColor: '#0f766e', color: '#ffffff', padding: '12px 20px', borderRadius: '6px' }}> See the repair </Button> </Container> </Body> </Html>)
export const repairReady = defineEmail({ name: 'repair-ready', subject: ({ bike }: RepairReady) => `Your ${bike} is ready for pickup`, component: RepairReadyEmail,})defineEmail option |
|
|---|---|
name |
Names the email in errors. |
subject |
The subject line, or a function of the data that makes it. |
component |
The body, a React component of the data. It is rendered with React Email’s render to the HTML part; the plain-text part is made from that HTML, leaving out what React Email marks to skip, such as <Preview>. |
headers |
Optional: more header fields, or a function of the data that makes them. A value is one line. |
bulk |
Optional: true marks bulk mail, which carries a one-click unsubscribe from its topic (see Unsubscribe). |
topic |
The kind of mail, such as newsletter, which a recipient unsubscribes from; required with bulk. |
The template that comes back has two methods, both typed by the component’s props:
render(data)gives{ subject, html, text, headers }without sending anything: for a test, or to look at the result.send(to, data, mailer?)renders and sends it, throughmailerwhen given (a job’smail), otherwise throughPROTOBASE_SMTP_URL. It rejects when mail is off or the server refuses the message, and a bulk email without a job’smailasmailer.
React and React Email’s renderer are loaded on the first email rendered, not when the app starts.
Mail an app sends in bulk, such as alerts or newsletters, is marked bulk with a topic, and Protobase gives it a one-click unsubscribe: see Unsubscribe.
The look of Protobase’s own mail
Section titled “The look of Protobase’s own mail”@protobase/server/email exports React Email components with the look of Protobase’s own mail, so an app’s defineEmail emails can look the same: a white card on grey with a teal action.
| Component | |
|---|---|
EmailLayout |
The whole email: preview, the line inboxes show after the subject; heading; the message as its children; and a footer naming app, linked to its home page. app is { name, url }. |
EmailButton |
The email’s one action: a button to href, and the label with the link in the plain-text part. |
EmailCode |
A code to type in, on a line of its own. |
EmailNote |
A remark below the message, such as why the recipient gets the email. |
import { defineEmail } from '@protobase/server'import { EmailButton, EmailLayout, EmailNote, type MailingApp } from '@protobase/server/email'import { Text } from 'react-email'
type RepairReady = { app: MailingApp; customer: string; bike: string; url: string }
const RepairReadyEmail = ({ app, customer, bike, url }: RepairReady) => ( <EmailLayout app={app} preview={`Your ${bike} is ready for pickup`} heading="Ready for pickup"> <Text>Hi {customer}, your {bike} is ready.</Text> <EmailButton href={url}>See the repair</EmailButton> <EmailNote>You get this email because you brought your bike in for repair.</EmailNote> </EmailLayout>)
export const repairReady = defineEmail({ name: 'repair-ready', subject: 'Your bike is ready', component: RepairReadyEmail })They are apart from @protobase/server itself, so an app that imports none never loads React Email’s components.
Sending
Section titled “Sending”A job is the usual place: it runs after the write that asked for it has committed, and a message the server refuses fails the try, which is retried. Pass the job’s mail, so a job runtime started with a mailer of its own sends through it:
import { FatalJobError, type JobRun } from '@protobase/server'import { repairReady } from '../emails/repair-ready'
// Enqueued by the write hook of a repair that became ready (hooks/email-ready-repair.ts), so the email goes out only// once the write has committed, and a refused message is retried.export default (async ({ repairId }, { db, mail }) => { if (!mail) throw new FatalJobError('Mail is off: set PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM') const repair = await db .selectFrom('repairs') .innerJoin('customers', 'customers.id', 'repairs.customer_id') .select(['repairs.number', 'repairs.bike', 'customers.name', 'customers.email']) .where('repairs.id', '=', repairId) .executeTakeFirst() if (!repair?.email) return const url = `https://bikeshop.example.com/repairs/${repair.number}` await repairReady.send(repair.email, { customer: repair.name, bike: repair.bike, number: repair.number, url }, mail)}) satisfies JobRun<{ repairId: number }>A write hook runs in the write’s transaction, which may still roll back. It enqueues the job rather than sending, so the email goes out only for a write that committed:
import { enqueueJob, type PipelineHook } from '@protobase/server'
// The job commits with the write, or not at all: no email about a change that was rolled back.export default (async (event, trx) => { if (event.resource.name !== 'repairs' || event.after?.status !== 'ready' || event.before?.status === 'ready') return await enqueueJob(trx, 'email-repair-ready', { repairId: Number(event.after.id) })}) satisfies PipelineHookimport { defineConfig } from '@protobase/config'
export default defineConfig({ jobs: { // jobs/email-repair-ready.ts 'email-repair-ready': { description: 'Emails a customer that their repair is ready for pickup.', arguments: { repairId: 'integer' } }, }, // hooks/email-ready-repair.ts writeHooks: ['email-ready-repair'],})An API function may send directly, as the answer to a request:
import { z } from 'zod'import { defineFunction, readJson } from '@protobase/server'import { repairReady } from '../emails/repair-ready'
const Input = z.object({ repairId: z.number().int().positive() })
// POST /api/functions/resend-repair-ready { "repairId": 7 }: the desk sends the email again, as the answer to the request.export default defineFunction({ roles: ['desk'] }, async (request, { records }) => { const { repairId } = await readJson(request, Input) const { record: repair } = await records.get('repairs', repairId) const { record: customer } = await records.get('customers', repair.customer_id as number) if (!customer.email) return Response.json({ sent: false, reason: 'The customer has no email address' }) const number = repair.number as string await repairReady.send(customer.email as string, { customer: customer.name as string, bike: repair.bike as string, number, url: `https://bikeshop.example.com/repairs/${number}` }) return Response.json({ sent: true })})A message is sent once per call, so a job try that sends and then fails sends again: record what was sent, and check it first.
Message id
Section titled “Message id”mail.send and a template’s send resolve to { messageId }, the Message-ID header the recipient sees, such as <[email protected]>. Store it with the record the mail was about, so a reply, bounce or complaint that comes back later, which names that id, can be matched to the mail it answers. A mailer that does not know the id resolves to {}, so store null then:
const { messageId } = await invoiceEmail.send(client.email, { number: 7 }, mail)await db.updateTable('invoices').set({ message_id: messageId ?? null }).where('id', '=', invoice.id).execute()Protobase gives every message through PROTOBASE_SMTP_URL a new id on the sender’s domain before it goes out, in place of a Message-ID among the message’s own headers. A relay that rewrites the Message-ID changes what the recipient sees, so check that yours keeps it. A mailer of the project’s own resolves to the id it sends, or to {} without one; mail from someone’s own mailbox resolves to {} (see below).
Unsubscribe
Section titled “Unsubscribe”Mail you mark as bulk carries a one-click unsubscribe, as large mailbox providers expect of bulk senders (RFC 8058): the mail client shows an unsubscribe button, and one click stops that kind of mail to that recipient. Protobase records who unsubscribed from which topic, and does not send that topic to them from the next send on.
Bulk is mail the recipient did not ask for by an action of their own: newsletters, digests, announcements and marketing. Transactional mail answers something the recipient did or needs to act on, such as a password reset, a sign-in code, a receipt or an invoice: it is not marked bulk and carries no unsubscribe. Protobase’s own mail is transactional.
Turn it on in the config, then run protobase migration, which writes its table, mail.unsubscribes, as a migration of the project’s own, and apply it with the project’s migrations: protobase serve refuses to start while the record of migrations lacks the table, and names the migration to write. Its links are on the app’s url, which must be https:// but on localhost, and signed with its secret:
export default defineConfig({ unsubscribe: true })Mark an email as bulk with a topic, the kind of mail someone unsubscribes from, such as newsletter or weekly-digest: a lowercase letter, then lowercase letters, digits, _ and -. Send it from a job with the job’s mail:
export const weeklyDigest = defineEmail({ name: 'weekly-digest', subject: 'This week', component: Digest, bulk: true, topic: 'weekly-digest' })
const { skipped } = await weeklyDigest.send(member.email, digest, mail)await mail.send({ to: member.email, subject: 'News', text: '...', bulk: true, topic: 'newsletter' })- The headers: each message gets
List-Unsubscribewith the recipient’s own link,https://<app>/api/unsubscribe/<token>with the defaultapiPath, andList-Unsubscribe-Post: List-Unsubscribe=One-Click, in place of such headers of its own. The token names the recipient and the topic, signed so that nobody can change either: a link cannot be made for someone else or for another topic. It is a bearer link, though: whoever holds it, such as someone the mail was forwarded to, can unsubscribe its recipient from its topic. - The button: mail clients show their unsubscribe button only on mail whose DKIM signature covers both headers. Protobase sends the headers; the server that signs your mail must sign
List-UnsubscribeandList-Unsubscribe-Posttoo, or the mail still goes out without a button. - A message per recipient:
totakes one plain address or several separated by commas, and each recipient gets a message of their own with their own link. A named address (Ada <[email protected]>) is refused. - The click: the mail client’s
POSTwithList-Unsubscribe=One-Clickrecords the opt-out and answers200; doing it again changes nothing. Opening the link in a browser shows a page with an Unsubscribe button that sends thatPOST, so a scanner that follows links in mail unsubscribes no one. A link the app did not sign answers400and records nothing. - Skipped sends: whoever unsubscribed from the topic is left out, found in one query, and the send resolves to them as
skippedbesidesent, each recipient it went to with its message id:{ skipped: ['[email protected]'], sent: [{ to: '[email protected]', messageId: '<…>' }], messageId: '<…>' }, withmessageIdonly when it went to exactly one. Other topics still reach them. Who unsubscribed is read once, before the first message goes out; one who unsubscribes while a send to several is going out is skipped from the next send on. - A refused message: when the server refuses one recipient’s message, the send rejects with a
BulkMailError(exported by@protobase/server, itscodeBULK_MAIL_FAILED) after the messages before it went out. It fails the try, which is retried, and names the recipient it failed on asto, those it went to assent, those skipped asskipped, and the server’s error ascause. A retried try sends to everyone again, so catch it, recorderror.sent, rethrow, and leave those addresses out of the next try; or send to one recipient per call. - From a workflow: a workflow’s mail steps send bulk mail as an email series, whose name is the topic.
- Who unsubscribed: admins see each recipient, topic and time under Unsubscribes in the admin app, and the app’s code reads them as the
mail_unsubscribesresource,GET /api/v1/mail_unsubscribes?filter=topic = "newsletter". Nobody changes them but the link. - Refused:
bulkwithout atopicis refused, as the email is defined or the message sent. Bulk mail withoutunsubscribe: true, or sent another way than a job’smail, such as throughPROTOBASE_SMTP_URLdirectly or from someone’s own mailbox, is refused before anything is sent. A mailer of the project’s own (auth/mailer.ts) that is handed bulk mail directly, outside a job’smail, gets it without its unsubscribe: send it through the job’smailinstead. -
Bulk mail cannot be sent from an API function because only a job’s mailadds the unsubscribe; enqueue a job instead. -
Email templates cannot be marked bulk because defineTemplatedoes not takebulkandtopicyet.
Bounces and complaints
Section titled “Bounces and complaints”A mail provider tells the app when a message bounced or its recipient marked it as spam. With mailFeedback on, each report becomes a mail_feedback record, one per recipient, or one for a complaint that hides who complained, with the events mail_feedback.bounced and mail_feedback.complained, which workflows, subscriptions and your own code act on, such as marking a contact’s address undeliverable. Protobase records and notifies only: it keeps sending to the address, and the app decides what a bounce means.
Turn it on in the config, then run protobase migration, which writes its table, mail.feedback, and the capture of its events as migrations of the project’s own; apply them with the project’s migrations, as protobase serve refuses to start while the record of migrations lacks the table:
export default defineConfig({ mailFeedback: true })Each provider reports to POST /api/mail/feedback/<provider> with the default apiPath, without sign-in, and has that endpoint only once its variable is set:
| Provider | Variable | |
|---|---|---|
ses |
PROTOBASE_MAIL_FEEDBACK_SES_TOPICS |
The ARNs of the SNS topics SES publishes bounces and complaints to, separated by commas. Subscribe the endpoint to each topic over HTTPS: the endpoint confirms the subscription itself. |
resend |
PROTOBASE_MAIL_FEEDBACK_RESEND_SECRET |
The webhook’s signing secret, whsec_..., of a webhook that sends email.bounced and email.complained to the endpoint. |
protobase |
PROTOBASE_SECRET |
The platform secret, which a hosting platform reports bounces and complaints with. |
A value that is not a topic ARN or a signing secret stops startup, naming the variable.
- Signatures: a report writes nothing unless its signature checks out.
sestakes SNS’s signature, versions 1 and 2, with the signing certificate fetched from an SNS host over HTTPS and kept an hour, and only messages of the named topics, since anyone can sign with a topic of their own.resendandprotobasetake Standard Webhooks signatures, made at most five minutes before. A missing or wrong signature answers401, another topic403. - The record:
typeisbounceorcomplaint;bounce_typehard(permanent) orsoft(transient), and empty when the provider could not tell;recipient, lower-cased, which a complaint leaves empty when the report hides who complained, as some mailbox providers’ spam reports do, and then names itsmessage_id;message_id, theMessage-IDheader of the message it is about, when the report states it;provider_message_id, the provider’s own id of that message;reason, as the provider gives it, such as the receiving server’s diagnostic, a bounce subtype or a complaint’s feedback type;occurred_at, when the provider says it happened;provider,event_id, the provider’s id of the report, andcreated_at. A value the report does not state is empty, never guessed. Match it to the mail it answers by the message id you stored. - Once: a provider sends a report again when it got no answer in time; the same report writes nothing new. A report of another kind, such as a delivery, answers
204and writes nothing. - Who sees it: admins see the reports under Mail feedback in the admin app, and the app’s code reads them as the
mail_feedbackresource,GET /api/v1/mail_feedback?filter=recipient = "[email protected]", filtered byrecipient,type,message_idorprovider_message_id. Nobody changes them but the endpoints. - The
protobaseendpoint: its body is one record as above, withoutprovider,event_idandcreated_at, such as{ "type": "bounce", "bounce_type": "hard", "recipient": "[email protected]", "message_id": "<...>", "reason": "smtp; 550 5.1.1 user unknown" }, a bounce with itsrecipientand a complaint with itsrecipient, itsmessage_idor both, signed as Standard Webhooks with a key derived fromPROTOBASE_SECRET, so the secret itself never travels:mailFeedbackHeaders(secret, id, body)of@protobase/servermakes the headers.webhook-idnames the report, and a retry keeps it. -
The generated type of a mail_feedbackrecord cannot say thatmessage_idis set whenrecipientis empty because field types that depend on another field’s value are not implemented. -
Other mail providers cannot report bounces and complaints because only the ses,resendandprotobaseendpoints are implemented.
Attachments
Section titled “Attachments”A message takes files beside its body, such as an invoice’s PDF: attachments, each a filename, its bytes as content (a Uint8Array, such as a Buffer) and, optionally, its contentType, else the one the name implies. A template’s send takes them as its fourth argument:
await invoiceEmail.send(client.email, { number: 7 }, mail, { attachments: [{ filename: 'invoice-7.pdf', content: pdf, contentType: 'application/pdf' }] })await mail.send({ to: client.email, subject: 'Invoice 7', text: 'Attached.', attachments: [{ filename: 'invoice-7.pdf', content: pdf }] })An attachment is only the bytes given: a file path or URL is never read in its place. A mailer of the project’s own (auth/mailer.ts) gets them in message.attachments.
From someone’s own mailbox
Section titled “From someone’s own mailbox”An app can send mail from the signed-in person’s own mailbox instead of the app’s address, such as an invoice from the account holder’s Gmail, so replies reach them. They link the mailbox once on the account page (“Connect Gmail” under Mailbox), which asks the provider for leave to send mail and nothing else; the app’s functions then send through it. auth.personalMail names the providers people may link, each through the app’s sign-in provider of the same company; Gmail links through Google sign-in (see Send mail from Gmail for the Google setup):
export default defineConfig(({ env }) => ({ auth: { socialProviders: { google: { clientId: env.GOOGLE_CLIENT_ID!, clientSecret: env.GOOGLE_CLIENT_SECRET! } }, personalMail: ['gmail'], encryptOAuthTokens: true, },}))A protected API function gets the caller’s mailbox as personalMail, a mailer like any other, so a template sends through it too:
import { defineFunction } from '@protobase/server'import { invoiceEmail } from '../emails/invoice'
export default defineFunction(async (request, { personalMail }) => { const { to, number, pdf } = await readInvoice(request) await invoiceEmail.send(to, { number }, personalMail, { attachments: [{ filename: `invoice-${number}.pdf`, content: pdf, contentType: 'application/pdf' }] }) return new Response(null, { status: 204 })})-
Tokens: the link is the sign-in provider’s account Better Auth keeps for the person, with its access and refresh tokens, encrypted:
auth.personalMailneedsencryptOAuthTokens: true, and startup stops without it. The tokens never leave the server. An access token that has expired is refreshed before the message goes out, and the new one is stored. -
When it cannot send:
sendrejects with aPersonalMailErrorand sends nothing. Itscodeisnot_linkedwhen the person linked no mailbox, or signed in with Google without allowing it to send mail, andlink_expiredwhen the provider no longer honours the link, as when they revoked it or its refresh token expired: they connect it again under Account → Mailbox. Thrown on, it answers the function’s caller as a409problem with thatcode(urn:protobase:problem:personal-mail-not-linkedor-link-expired), and an action whose handler gets it offers to connect the mailbox right there:{ "type": "urn:protobase:problem:personal-mail-link-expired", "status": 409, "code": "link_expired", "provider": "gmail" } -
Sender: without a From address, the provider sends as the linked address; Gmail sets the From header to it. A From address goes out through the connection its record is on, never through another.
-
Which account: mail goes out through the account the person connected for mail last. Connecting Gmail with another Google account takes the mail scopes off the earlier one in the app’s store, and signing in with the earlier one does not take the mail back; connecting it again does. When the chosen account’s link fails, sending fails: it never falls back to another account. Of two accounts that both still hold the mail scopes, as when both connected before this rule came in, mail goes through the one linked to the person last, until they connect one again.
-
Only the person: mail goes out from a mailbox only for someone signed in as themselves, or from a workflow step’s
mailboxin a version that person turned on while signed in as themselves, and only while they may still change the workflow. Staff signed in as them, an outside app acting for them, and a job’s own code cannot send from it; a request is refused with a403problem (own-sign-in-only), a step fails withnot_linked, and nothing is sent. Turning the workflow off, or someone else turning a new version on, ends the first person’s consent. -
Providers: Gmail, through Google sign-in. A provider is added to Protobase behind the same
PersonalMailProvidershape: its sign-in provider, the scopes linking asks for, and how it sends. -
Sign-in is not a mailbox: under Mailbox, the account page says when someone signs in with Google without having allowed it to send mail, so a linked Google sign-in is not taken for a connected mailbox.
-
The account page cannot show which account a mailbox is linked through or disconnect it because unlinking a mailbox is not implemented. -
Mailboxes other than Gmail cannot be linked because no other mail provider is implemented. -
Bounces: mail sent from someone’s own mailbox bounces back to the sender, not to the app. It reaches none of the mail feedback endpoints, so it makes no
mail_feedbackrecords and nobouncedorcomplainedevents. Handling its bounces is the sender’s own concern. -
A send through Gmail cannot return its message id because Gmail sets its own and reading it back needs a scope that reads the mailbox, which the link does not ask for.
From addresses
Section titled “From addresses”A mailbox may send as more than its own address, such as Gmail’s send-as addresses (Gmail’s settings → Accounts → Send mail as). Each From address is a record on one of the person’s mailbox connections, theirs alone, with a state that says whether the mailbox really sends as it. The account page lists them under Mailbox → From addresses.
-
Typed: the person adds an address with Add a From address, on the mailbox mail goes through. Until the provider lists it, it is Not checked (
unverified). -
Listed: a provider that can list the mailbox’s send-as addresses fills them in, with its own word on each. Gmail does this when the app adds the optional
gmail.settings.basicscope to the link: it reads the list and nothing else of the mailbox. The account page reads the list again each time it opens, and with Check with Gmail. -
States:
verified: the provider sends as it; for Gmail, an accepted send-as address, or the account’s own.pending: the owner still has to confirm it with the provider.failed: a complete listing since the address was added did not hold it, so Gmail would send from the account’s own address instead.unverified: nothing says either way.
Where the provider says nothing, a verifier of the app may prove the address
verified.The state is worked out each time it is read, from what typed the address and what the provider last listed. An address the listing leaves out keeps its record and its id: only its listed state goes.
-
Without the scope: a Gmail link without
gmail.settings.basicis told which scope it lacks. The account page then offers Allow address checks, which connects Gmail again asking for it, and sends the person back to the account page. -
Name: an address may carry a display name, which the From header shows beside it, such as
From: Shop billing <[email protected]>, as mail sent by hand from a send-as address shows the name set up for it; a name that is not ASCII is encoded. Left empty, the header holds the bare address. -
Signature: an address may carry its own signature, which takes the place of the app’s generic one; left empty, the generic one applies.
-
Default: one address, theirs or their mailbox’s own, is the one mail goes out from when the app names none.
-
Removing: removing an address hides it and keeps its record. Adding it again brings back the same record, and only a new listing counts for it after that.
To let Gmail list the send-as addresses, add the scope in the config, and add it to the Google client’s consent screen (Data Access) as well:
personalMail: [{ provider: 'gmail', scopes: [gmailSettingsScope] }], // import { gmailSettingsScope } from '@protobase/server'A function sends from a From address by naming its record. To send a template from it, render it and send the result:
export default defineFunction(async (request, { personalMail }) => { const { to, number, pdf } = await readInvoice(request) const email = await invoiceEmail.render({ number, signature: sender.signature ?? defaultSignature }) await personalMail.send({ sender_address_id: sender.id, to, ...email, attachments: [{ filename: `invoice-${number}.pdf`, content: pdf, contentType: 'application/pdf' }] }) return new Response(null, { status: 204 })})-
send({ sender_address_id, ... }): sends from that record’s address, with its display name, through that record’s own mailbox connection, so From and mailbox cannot disagree.nullsends from the mailbox’s own address with no From header, and leaving it out sends from the default address, else the mailbox’s own. A message that names its ownfromorsender, or aFromorSenderheader, is a mistake that rejects. An address no listing has read yet is listed first, when its provider can list. -
Refusals, each sending nothing:
- An id that is not one of the caller’s, unknown or removed alike, answers
404(sender-address-not-found), as does one someone else did not share with them. - A
failedaddress answers409withcode: "sender_address_failed", and apendingonesender_address_pending. - An address on no connection the person can send through answers
sender_address_detached. - An
unverifiedone is sent.
- An id that is not one of the caller’s, unknown or removed alike, answers
-
sender(address?): the record an address stands for, matched without regard to case:id(null for the mailbox’s own address),address,namewhen it has one,signaturewhen it has its own,state, andownerId, whose mailbox it goes through. One someone else shared with the caller comes after their own, withshared: trueand noownerId. Without an address, the default. An address that is neither the caller’s nor shared with them is refused with aMailSenderRefusedError(403); one on two of their connections, or shared by two people, withsender_address_ambiguous. -
senders(): every address the caller may choose, such as for a send dialog: their mailbox’s own, then their records, each with its id and state, then those shared with them. -
refresh(): reads the send-as addresses of each of the caller’s mailboxes whose provider can list them, and answers how each went:listed,not_permittedwithmissing_scopes, orerrorwithlink_expiredorlisting_failed. A connection that fails changes nothing and stops none of the others. -
The mailbox’s own address is the one its provider’s ID token names; Google gives it with the
emailscope sign-in asks for. -
The account page’s calls:
GET /api/auth/account/mail-senderslists the person’s addresses with theirstateandconnection, their mailbox’s ownaddress, and theirconnections, each withcanListand themissingScopesthe app adds that its link lacks.POST .../mail-senders/add { address, name?, signature?, connection? }types an address, onconnectionor else the mailbox mail goes through.POST .../mail-senders/update { id, name?, signature?, isDefault? }changes one:name: nulldrops the name andsignature: nullits own signature.POST .../mail-senders/remove { id }removes one.POST .../mail-senders/refreshreads the send-as addresses, asrefresh()does.
Each acts on the signed-in person’s own addresses and connections only: any other id answers
404before anything is done. -
Upgrading: an address entered before From addresses were records goes on its owner’s Gmail connection when they had exactly one. With none or several it shows No mailbox, and the person removes it and adds it again.
-
An address on a mailbox linked without gmail.settings.basiccannot be checked before each send because only a verification started from the account page is implemented for it.
Verifying a From address
Section titled “Verifying a From address”Gmail sends from the account’s own address, without an error, when a From address is not one of its verified send-as addresses, and a mailbox that cannot list its send-as addresses leaves an address unverified. A verifier proves such an address another way, such as by sending one test message from it and reading how it arrives. The app’s trusted code adds verifiers with add_verifier, from the project’s auth/hooks.ts:
import type { AuthHooks } from '@protobase/server'
export const senderVerifiers: AuthHooks['senderVerifiers'] = (add_verifier) => add_verifier(testMailVerifier)A host’s runtime can pass its own in createAuth’s senderVerifiers. A verifier is a SenderAddressVerifier:
const testMailVerifier: SenderAddressVerifier = { id: 'test-mail', verify: async ({ verification_id, address, secret, locale }, { send }) => { const to = await checkService.issue({ verification_id, secret }) await send({ to, subject: `Test message for ${address}`, text: 'This message checks that your mailbox sends from this address.' }) return { state: 'pending', expires_at: new Date(Date.now() + 10 * 60_000) } }, check: async ({ verification_id }) => checkService.result(verification_id),}-
id: stored on each verification, so it stays the same across releases: lowercase letters, digits,_,.and-, starting with a letter, at most 64 characters. Two verifiers with one id, or a verifier withoutauth.personalMail, stop startup. -
verify(input, tools): starts a verification ofaddress.tools.send({ to, subject, text, html? })sends one test message through the address’s own mailbox, From that address, to one recipient: a From, copies, headers or attachments it is given are left out, and a second send is refused. -
check(input): optional. The app’s sweep calls it each minute a pending verification is due, until it settles or expires. -
Outcomes:
verifyandcheckanswer one of these.{ state: 'pending', expires_at, check_after? }:verifymust nameexpires_at, which the app caps at 24 hours after the verification started.checkcannot move it. The next check comes atcheck_after, else a minute on, and never sooner than a minute on.{ state: 'verified', valid_until }:valid_untilis required, lies ahead, and is capped at 28 days.{ state: 'failed', error_code, error? }:error_codeis a lowercase name, such asfrom_rewritten.erroris plain text of at most 500 characters, with no control characters but line breaks and tabs, shown as text and never as markup.
An outcome that breaks these rules, or a
verifythat throws, fails the verification asverifier_error. The address’s state does not change. -
One at a time: an address has at most one pending verification per verifier. It is stored before
verifyruns, so starting it again sends nothing while it is pending. A verification whoseverifynever returned expires after 5 minutes, and the next start takes its place. -
Expiry: a verification still pending at
expires_atfails asverification_expired, from the sweep,auth.mail-sender-verifications, which runs each minute on the app’s jobs. -
Reports: an outside service settles a verification with
POST /api/auth/mail-sender-verifications/report, with this JSON body:{ verifier, secret, state: 'verified', valid_until }or{ verifier, secret, state: 'failed', error_code, error? }.secretis the oneverifywas given: 256 random bits, made for that verification alone. The app keeps only its SHA-256, so it is never handed out again. The verification’s id is not a secret.- The secret is read from the body only. Keep it out of URLs and logs.
- A report settles the verification only for the verifier that started it, while it is pending and before it expires, and once only. Whichever comes first wins: the report, the sweep or
verify’s own outcome. - Any report that settles nothing answers the same
403withcode: "VERIFICATION_REFUSED", whatever the reason. A malformed outcome answers400before anything is looked up.
-
The address’s state: a verified verification makes an address the provider says nothing of
verified, until itsvalid_until. It never outweighs what the provider says, such as afailedlisting. It counts only while its verifier is registered, and only if it settled after the address was last removed. A failed verification shows on the account page and leaves the state as it was. -
The account page: adding an address verifies it at once. Its dialog, under Edit, verifies it again with Verify address, and after a result with Verify again. While a verification is pending, the dialog reads it again every 3 seconds for up to 2 minutes. Without a verifier, the dialog says the app cannot verify From addresses, and how to check one by hand.
-
The account page’s calls:
GET /api/auth/account/mail-senderssaysverifiers: truewhen the app has any, and gives each address its latestverifications, one per verifier:verifier,state,expiresAtwhile pending,settledAt,validUntil,errorCodeanderror.POST .../mail-senders/verify { id }starts each verifier on one of the person’s addresses on a connection they can send through, and answers itsverifications.- Staff signed in as the person cannot start one.
Sharing a From address
Section titled “Sharing a From address”An address can be shared with the app’s other senders, such as a team’s billing address: they pick it like one of their own and send from it, through its owner’s mailbox. Only the owner shares or unshares it, on the account page, under Edit, with Share with the app’s other senders.
- Only a verified address: sharing one that is not
verified, by its provider’s listing or a verifier’s proof, is refused with a409(MAIL_SENDER_NOT_VERIFIED), and the dialog says to prove it first. Sharing records when it was shared and no proof of its own: every read works the state out again, as for the owner. - Who sees it: with organizations, the people who share an organization with the owner; without them, everyone who sends mail in the app. They see its id, address and display name only, never the owner’s address, id or mailbox.
- Sending:
send({ sender_address_id })with a shared address’s id goes out through the owner’s mailbox, From that address, with its display name, while it is shared, stillverifiedand its owner still in reach. Otherwise it answers404(sender-address-not-found), as for an address that is not theirs. When the owner’s mailbox is gone or its link expired, it answers409withcode: "sender_address_owner_unlinked": the owner must connect their mailbox again, so no connect offer is made to the sender. - Adding never shares, and removing an address unshares it: added again, it is the owner’s alone until they share it again. Unsharing always works.
- The account page’s calls:
GET /api/auth/account/mail-sendersgives each shared address of the person’s asharedAt, and lists those others shared with them asshared, each{ id, address, name? }.POST .../mail-senders/share { id }shares one of the person’s addresses, andPOST .../mail-senders/unshare { id }makes it theirs alone again; each answers the address. Any other id answers404.- Staff signed in as the person can do neither.
A From address on a record
Section titled “A From address on a record”A record can hold the address its mail goes out from, such as a client’s or the seller’s “Send from”: declare the field with f.mailSender(), on a text column, and send from it with send({ sender_address_id: (await personalMail.sender(value)).id }).
send_from: f.mailSender().optional(),-
The form: a dropdown of the signed-in person’s addresses, their mailbox’s own first, then their records, then the addresses others shared with them, marked shared, each as
Name <address>when it has a name, followed by its state unless it is verified. An address mail cannot go out from, onefailedorpending, shows but cannot be chosen, unless the record holds it already. The empty choice, Sender’s default address, storesnull: mail goes out from the default address of whoever sends it. -
Saving: a create or update may only set an address the saving person may send from, by the rule
senduses; the address is stored as their sender spells it. Any other is refused with a400naming the field and the address. A visitor, and anyone on an app without personal mail, can set none. -
An address no longer offered, such as one another person entered, still shows, marked not available, with a link to the account page. Saving other fields, or giving the same address again, leaves it as it is.
-
Read views show the address, with its name when it is one of the reader’s.
-
Removing an address in use: while a record that is not soft-deleted holds it in an
f.mailSender()field, removing it on the account page, or disconnecting the mailbox whose own address it is (POST /api/auth/unlink-account), is refused with a409and changes nothing:{ "code": "MAIL_SENDER_IN_USE", "message": "[email protected] is still the From address of records in this app. Give them another From address first." }The refusal names no records, since they may be records the person cannot read, such as another organization’s. It is in the language the request’s
Accept-Languageasks for. The address is matched without regard to case, as sending matches it, so an index on the column’slower()serves it. -
A refused removal cannot name the records that hold the address because checking which of them the person may read is not implemented. -
Unsharing an address in use always works: a record that holds it keeps it, shows it as not available to everyone else, and a send from it is refused.
In a bundle
Section titled “In a bundle”A bundle gets React and React Email’s renderer from the serve runtime, as it gets @protobase/server and @protobase/server/email, so an email’s component and the renderer share one React and hooks such as useContext work. React Email’s other components are inlined, though @protobase/server uses them too: it loads them only to send its own mail, so the runtime does not supply them. Its <Tailwind> component needs tailwindcss, which the runtime does not supply, so a served config cannot use it: style with style props instead.