@mavonengine/mail sends mail from the game server: welcome mails, password resets, receipts. Mail goes on the server's job queue and is tried again when the mail server is down, so a slow or failing provider never holds up the game.
npx @mavonengine/cli install @mavonengine/mail
Until you set up a transport, mail is written to the server's log instead of sent, so you can build and test mail in development without an account anywhere.
With it, @mavonengine/auth confirms emails and resets forgotten passwords, and @mavonengine/notifications mails notifications.
Sending mail
Write a mail as a class that extends Mailable:
import { escapeHtml, Mailable } from '@mavonengine/mail'
export class Welcome extends Mailable {
constructor(private name: string) {
super()
}
subject() {
return `Welcome, ${this.name}!`
}
// The line inboxes show next to the subject
preheader() {
return 'Your account is ready'
}
text() {
return `Good to have you, ${this.name}.`
}
html() {
// Escape what players wrote before it goes into html
return `<p>Good to have you, <b>${escapeHtml(this.name)}</b>.</p>`
}
}
In a plugin, the mail plugin is ctx.plugin('@mavonengine/mail'). It is undefined when the project doesn't have it, so a plugin can make mail optional:
export default defineServerPlugin({
http(app, ctx) {
app.post('/api/shop/buy', async (req, res) => {
const order = await buy(req.body)
await ctx.plugin('@mavonengine/mail')?.to(order.email).send(new Receipt(order))
res.json(order)
})
},
})
In the game's server code, use mail(server):
import { mail } from '@mavonengine/mail'
await mail(server)?.to('Ada <ada@example.com>').cc('team@example.com').send(new Welcome('Ada'))
- Queued by default:
send()resolves once the mail is on the queue, with{ queued: true, jobId }. The queue tries it 3 times, waiting 10 seconds and then a minute, and keeps it among the failed jobs asmail:sendwhen every try failed. With a database plugin, queued mail survives a restart. - Right away:
sendNow()sends in the call and rejects when the transport does. So do a mailable withqueued = falseandsend(mailable, { queued: false }).send(mailable, { delayMs })sends it later. - Checked when you send: a mail without a recipient, a subject or a text or html, with an address that isn't one, or with a line break in its subject, a name or a header, makes
send()throw aMailError. You find out right away, not in the log when the queue gets to it. - Rendered when you send: what waits on the queue is the finished mail as plain JSON, not the class.
- Written out:
send({ to, subject, text, html })sends a mail without a class.
from, replyTo and headers() can be set per mailable. A mail without a from gets the one from the options.
Layout
HTML mail is sent in a layout: the game's name at the top, the mail on a white card and a footer below. A mail with only text gets html made from it, a paragraph per blank line, so every mail looks the same. Write html() as what goes inside the layout, not as a whole page.
To change the layout, publish it into the project with asset:publish:
npx @mavonengine/cli asset:publish @mavonengine/mail
That copies it to resources/@mavonengine/mail/layout.html, which is used from then on. Outside production the file is read again for every mail, so a change shows in the next one without a restart.
{{ name }} is filled in escaped, {{{ name }}} as it is:
{{{ content }}} | The mail's html, or its text made into paragraphs |
{{ subject }} | The subject |
{{ preheader }} | From the mailable's preheader(), or preheader in send() |
{{ appName }} | The game's name, appName in mavonengine.json, else the sender's name |
{{ appUrl }} | Where the game is, appUrl in mavonengine.json or MAVONENGINE_APP_URL. Empty when it isn't set |
{{ year }} | This year |
| anything else | From the layoutData option, e.g. {{ footer }} |
Comments are left out of the mail, apart from Outlook's conditional comments (<!--[if mso]>). Mail clients ignore most CSS and <style> blocks, so keep to tables and inline styles, as the default layout does.
A mailable with layout = false, or send({ …, layout: false }), is sent without the layout; the layout option turns it off for all mail. When the layout can't be read, mail goes out without it and the log says so.
Transports
Mail goes through one transport at a time.
SMTP
Almost every provider has an SMTP relay: Mailgun, Amazon SES, Postmark, SendGrid, Resend or your own server. Put the server in the options and the password in the environment:
{
"plugins": {
"@mavonengine/mail": {
"options": {
"from": "My Game <noreply@mygame.com>",
"smtp": { "host": "smtp.mailgun.org", "port": 587, "user": "postmaster@mg.mygame.com" }
}
}
}
}
MAVONENGINE_MAIL_SMTP_PASSWORD=… npm start
Or put everything in one URL: MAVONENGINE_MAIL_SMTP_URL=smtps://user:password@smtp.example.com. Port 465 connects with TLS; other ports upgrade with STARTTLS when the server offers it.
Nodemailer transports
Mail is sent with nodemailer, so its transports work too. Those are objects rather than JSON, so set them up in code:
import { SendEmailCommand, SESv2Client } from '@aws-sdk/client-sesv2'
import { mail } from '@mavonengine/mail'
mail(server)?.useNodemailer({ SES: { sesClient: new SESv2Client({ region: 'eu-west-1' }), SendEmailCommand } }, 'ses')
Community transports such as nodemailer-mailgun-transport work the same way.
Your own
A transport is an object with a name and a send() that resolves once the mail was handed over. That is all a provider's plugin needs:
import type { MailTransport } from '@mavonengine/mail'
import { formatAddress } from '@mavonengine/mail'
const postmark: MailTransport = {
name: 'postmark',
async send(message) {
const res = await fetch('https://api.postmarkapp.com/email', {
method: 'POST',
headers: { 'X-Postmark-Server-Token': token, 'Content-Type': 'application/json' },
body: JSON.stringify({ From: formatAddress(message.from!), To: message.to.map(formatAddress).join(', '), Subject: message.subject, TextBody: message.text, HtmlBody: message.html }),
})
if (!res.ok)
throw new Error(`Postmark answered ${res.status}`)
return { messageId: (await res.json()).MessageID }
},
}
ctx.plugin('@mavonengine/mail')?.useTransport(postmark)
send() should reject when the mail wasn't taken, so the queue tries it again. A close(), when the transport has one, is called when it is replaced and when the server stops.
In tests
memoryTransport() keeps mail in its sent array instead of sending it:
import { mail, memoryTransport } from '@mavonengine/mail'
const memory = memoryTransport()
mail(server)!.useTransport(memory)
// …
expect(memory.sent[0].subject).toBe('Welcome, Ada!')
Options
Set them under the plugin in mavonengine.json. All are optional.
| Option | Default | |
|---|---|---|
from | The sender of mail that names none, like My Game <noreply@mygame.com>. Needed for every transport but the log | |
smtp | The SMTP server: { host, port, secure, user }, or a URL without the password. See SMTP | |
queued | true | Queue mail, or send it in the call. A mailable's queued and the options of send() win over it |
queue | default | The queue mail goes on. Give mail a queue of its own, with the server's queue.queues, to keep it from waiting behind other jobs |
tries | 3 | How often a queued mail is tried before it counts as failed |
backoffMs | [10000, 60000] | How long to wait before trying again, in ms: one number, or one per retry with the last repeating |
layout | true | Send mail in the layout |
layoutData | {} | More values for the layout, e.g. { "footer": "You get this because you play My Game." } |
| Environment | |
|---|---|
MAVONENGINE_MAIL_FROM | Overrides from |
MAVONENGINE_MAIL_SMTP_URL | The SMTP server with its credentials, overriding smtp |
MAVONENGINE_MAIL_SMTP_PASSWORD | The password for smtp. Keep it out of mavonengine.json |
Attachments and a view of sent mail in the dashboard aren't there yet.