Skip to content

Mail ​

Introduction ​

@plinthjs/mail sends email without tying your application code to a delivery service. You describe a message as a mailable, hand it to a mailer, and the mailer passes it to a transport that does the actual delivery. Because the transport is a small interface, you can swap an in-memory transport for tests, a log transport for local development, and your own transport for production without touching the mailables.

bash
pnpm add @plinthjs/mail

INFO

The package ships two transports: ArrayTransport, which keeps messages in memory, and LogTransport, which writes them to a sink. Neither touches the network. To deliver through SMTP or a provider API, implement the Transport interface (see Writing a transport).

Sending mail ​

Build a Mailable, create a Mailer around a transport, and call send.

ts
import { ArrayTransport, Mailable, Mailer } from '@plinthjs/mail'

const transport = new ArrayTransport()
const mailer = new Mailer(transport)

const receipt = await mailer.send(
  new Mailable()
    .from({ email: 'no-reply@app.com', name: 'App' })
    .to('ada@example.com')
    .subject('Welcome')
    .html('<h1>Hello</h1>'),
)

receipt.id // => 'array-1'
transport.sent[0].subject // => 'Welcome'

send resolves with a receipt holding the transport's message id and the final message.

Recipients can be an address string, an { email, name } object, or an array of either. to, cc, bcc and replyTo all accept the same shapes and add to whatever is already set.

ts
new Mailable()
  .to(['ada@example.com', { email: 'grace@example.com', name: 'Grace' }])
  .cc('manager@app.com')
  .bcc('audit@app.com')
  .replyTo('support@app.com')

Choosing the recipient first ​

mailer.to(...) returns a pending mail so you can name the recipients before the mailable.

ts
await mailer
  .to('ada@example.com')
  .cc('manager@app.com')
  .send(new Mailable().subject('Hi').text('Hey'))

The pending mail also has queue and later (see Queued mail).

Quick plain-text mail ​

For a one-off message, raw builds a plain-text mailable and lets you configure it.

ts
await mailer.raw('Heads up', (mail) => mail.to('ops@app.com').subject('Notice'))

Writing mailable classes ​

A fluent Mailable is fine for one-offs. For anything you send in more than one place, subclass it. There are two styles, and you can mix them.

Using envelope, content and attachments ​

Override envelope(), content() and attachments() to describe the message declaratively. The mailer calls them before sending.

ts
import { Attachment, Content, Envelope, Mailable } from '@plinthjs/mail'

class OrderShipped extends Mailable {
  constructor(private readonly orderId: number) {
    super()
  }

  override envelope() {
    return new Envelope({
      from: 'shop@app.com',
      subject: `Order #${this.orderId} shipped`,
      tags: ['orders'],
      metadata: { order: this.orderId },
    })
  }

  override content() {
    return new Content({
      markdown: ['# Shipped', '', 'Your order **is** on its way.'],
      with: { orderId: this.orderId },
    })
  }

  override attachments() {
    return [Attachment.fromPath('/var/invoices/42.pdf', { as: 'invoice.pdf' })]
  }
}

await mailer.to('ada@example.com').send(new OrderShipped(42))

An Envelope takes from, to, cc, bcc, replyTo, subject, tags and metadata. A Content takes one of markdown, html, text or view, plus a with object of view data. Values set directly on the mailable (with .subject(), .html() and so on) win over the envelope and content: the envelope only fills in from and subject when they are not already set, and content only fills in bodies that are still empty. Recipients, tags and attachments from the envelope are added to the ones already present.

Using build ​

The older style is a single build() method that calls the fluent API.

ts
class Welcome extends Mailable {
  constructor(private readonly name: string) {
    super()
  }

  override build(): void {
    this.subject(`Welcome, ${this.name}`).html(`<p>Hello ${this.name}</p>`)
  }
}

The mailer prepares a mailable once, running build(), then envelope(), content() and attachments(), so sending the same instance twice does not duplicate recipients.

Other message settings ​

ts
new Mailable()
  .tag('onboarding') // provider tag, repeatable
  .metadata('user_id', 42) // string or number values
  .priority('high') // 'highest' | 'high' | 'normal' | 'low' | 'lowest'
  .text('Plain text body')

with(key, value) and with({ ... }) attach view data, and view(name, data) records a template name and its data on the message. The package does not include a template engine: view sets the message's view and viewData fields (and uses the template name as the HTML body until something replaces it), so a transport or your own renderer decides what to do with them.

Markdown mail ​

markdown(lines) renders a small Markdown subset into both an HTML body and a plain-text body, so one source gives you both parts. It supports headings, paragraphs, bullet lists (- or *), block quotes, and inline bold, italic and code. HTML in the source is escaped.

ts
const mail = new Mailable()
  .to('ada@example.com')
  .subject('Report')
  .markdown(['## Weekly report', '', 'You have **3** new `tasks`.', '', '- one', '- two'])

mail.render().html
// => '<h2>Weekly report</h2>\n<p>You have <strong>3</strong> new <code>tasks</code>.</p>\n<ul>...'
mail.render().text
// => 'Weekly report\n\nYou have 3 new tasks.\n\n- one\n- two'

You can also call renderMarkdown(lines) directly. It returns { html, text } without creating a mailable.

Attachments ​

attach takes a file path (with optional as and mime options) or an Attachment. The Attachment helper builds the three kinds:

ts
import { Attachment } from '@plinthjs/mail'

mail.attach('/var/invoices/42.pdf', { as: 'invoice.pdf', mime: 'application/pdf' })
mail.attach(Attachment.fromPath('/var/invoices/42.pdf'))
mail.attachData('col1,col2', 'export.csv', { mime: 'text/csv' }) // from memory
mail.attach(Attachment.fromUrl('https://example.com/files/report.pdf')) // fetched at send time
mail.attachMany([Attachment.fromData('hello', 'note.txt'), Attachment.fromPath('/tmp/a.png')])

When no name is given, the filename comes from the last segment of the path or URL.

A URL attachment is downloaded with fetch when the mailer sends the message. The bytes replace the URL, and the content type comes from your mime option or the response's Content-Type header. A non-2xx response makes send reject with Failed to fetch attachment [url]: HTTP 404.. Path attachments are passed to the transport as-is, so reading the file is up to the transport.

Global addresses ​

A mailer can apply defaults to every message it sends.

ts
const mailer = new Mailer(new ArrayTransport())
  .alwaysFrom('hello@app.com', 'App')
  .alwaysReplyTo('support@app.com')
  .alwaysReturnPath('bounce@app.com')

alwaysFrom is used only when the message has no sender of its own. alwaysReplyTo adds a reply-to address unless it is already there. alwaysReturnPath sets a Return-Path header.

alwaysTo redirects every message to one address, which is useful in staging so real customers are never emailed. The original recipients are preserved in X-To, X-Cc and X-Bcc headers, and cc and bcc are cleared.

ts
const transport = new ArrayTransport()
const staging = new Mailer(transport).alwaysTo('dev@app.com')

await staging.send(new Mailable().to('real@customer.com').subject('Hi').text('Hi'))

transport.last()?.to // => [{ email: 'dev@app.com' }]
transport.last()?.headers // => { 'X-To': 'real@customer.com' }

Mail events ​

Pass an events object (anything with a dispatch(event) method) in the mailer options. It receives a MessageSending event just before the transport is called, with the final message, and a MessageSent event afterwards, with the sent receipt. A Dispatcher can be passed directly (events: dispatcher), then dispatcher.listen(MessageSent, ...).

ts
import { MessageSending, MessageSent } from '@plinthjs/mail'

const mailer = new Mailer(new ArrayTransport(), {
  events: {
    dispatch(event) {
      if (event instanceof MessageSending) console.log('sending', event.message.subject)
      if (event instanceof MessageSent) console.log('sent', event.sent.id)
    },
  },
})

Queued mail ​

Sending mail inside a request makes the request wait for the provider. The mailer has queue(mailable) and later(seconds, mailable) for deferring it, but it does not own a queue. You give it a queue seam: a function that receives { mailable, delay? } and decides what to do, typically by pushing a job onto a queue that sends the mailable.

ts
import { ArrayQueue, Job } from '@plinthjs/queue'

const queue = new ArrayQueue()

class SendMail extends Job {
  constructor(
    private readonly mailer: Mailer,
    private readonly mailable: Mailable,
  ) {
    super()
  }

  async handle() {
    await this.mailer.send(this.mailable)
  }
}

const mailer: Mailer = new Mailer(new ArrayTransport(), {
  queue: async ({ mailable, delay }) => {
    const job = new SendMail(mailer, mailable)
    if (delay === undefined) await queue.push(job)
    else await queue.later(delay, job)
  },
})

await mailer.to('ada@example.com').queue(new Welcome('Ada')) // pushed, not sent
await mailer.to('ada@example.com').later(60, new Welcome('Ada')) // delayed
await queue.work() // sends the due one

Without a queue seam, queue and later simply send immediately.

Mailers and the mail manager ​

MailManager names several mailers and returns them on demand. array and log are built in, and default picks the one used when you do not name a mailer (array when omitted). Each mailer is created once and cached.

ts
import { ArrayTransport, Mailer, MailManager } from '@plinthjs/mail'

const manager = new MailManager({
  default: 'log',
  mailers: {
    ses: () => new Mailer(new MySesTransport()),
  },
  events: { dispatch: (event) => console.log(event) },
})

await manager.mailer().send(new Welcome('Ada')) // the default mailer
await manager.mailer('ses').send(new Welcome('Ada'))

manager.getDefaultMailer() // => 'log'
manager.extend('backup', () => new Mailer(new ArrayTransport()))
manager.mailer('missing') // throws: Mailer [missing] is not defined.

The queue and events options are passed to the built-in array and log mailers, and logSink sets where the log mailer writes (console.log by default).

The built-in mailers create their transports for you, and the manager keeps them readable. manager.sent(name?) returns the messages the array mailer has sent, and manager.transport(name?) returns the ArrayTransport or LogTransport behind a built-in mailer (undefined for a mailer you registered yourself, since you own its transport).

ts
const manager = new MailManager()
await manager.mailer().send(new Welcome('Ada'))

manager.sent().length // => 1
manager.sent()[0]?.subject // => 'Welcome, Ada'
manager.transport('array') // the ArrayTransport
``` Mailers you supply through `mailers` or `extend` are built by your own factory, so pass those options to their constructors yourself.

::: tip
A generated app has `config/mail.ts` with a `default` mailer, a `mailers` map (`smtp`, `log`, `array`) and a `from` address. Those are configuration values for your application; the manager above takes its mailers as code, and `smtp` needs a transport you provide.
:::

## Transports

### Array transport

`ArrayTransport` records each message in `sent`. It also has `last()` and `flush()`.

```ts
const transport = new ArrayTransport()
await new Mailer(transport).send(new Mailable().to('a@a.com').subject('Hi').text('x'))

transport.sent.length // => 1
transport.last()?.subject // => 'Hi'
transport.flush()

Message ids look like array-1. Pass { sequence: () => number } to control the counter.

Log transport ​

LogTransport formats the message as headers followed by the body, and writes it to a sink. The default sink is console.log.

ts
import { LogTransport } from '@plinthjs/mail'

const lines: string[] = []
const mailer = new Mailer(new LogTransport((line) => lines.push(line)))

await mailer.send(
  new Mailable().from('a@a.com').to({ email: 'b@b.com', name: 'Bee' }).subject('Hi').text('Body'),
)

lines[0]
// => 'Message-Id: log-1\nFrom: a@a.com\nTo: Bee <b@b.com>\nSubject: Hi\n\nBody'

Writing a transport ​

A transport implements one method, send(message), and resolves with { id, message }.

ts
import type { EmailMessage, SentMessage, Transport } from '@plinthjs/mail'

class WebhookTransport implements Transport {
  async send(message: EmailMessage): Promise<SentMessage> {
    const response = await fetch('https://mail.example.com/send', {
      method: 'POST',
      body: JSON.stringify(message),
    })
    const { id } = (await response.json()) as { id: string }
    return { id, message }
  }
}

Previewing and rendering ​

render() prepares a mailable and returns the message as the transport would receive it, without sending anything. Use it to preview a mail, or to assert on it in a test.

ts
const message = new OrderShipped(42).to('ada@example.com').render()

message.subject // => 'Order #42 shipped'
message.html // => '<h1>Shipped</h1>...'
message.attachments[0]?.filename // => 'invoice.pdf'

A mailable also has assertion helpers that prepare it first and throw a descriptive error when they fail. They return the mailable, so they chain.

ts
new OrderShipped(42)
  .to('ada@example.com')
  .assertHasTo('ada@example.com')
  .assertHasSubject('Order #42 shipped')
  .assertSeeInHtml('<strong>is</strong>')
  .assertSeeInText('Your order is on its way')

assertHasCc and assertHasBcc check the other recipient lists.

Testing ​

For a unit test, send through a mailer built on ArrayTransport and read transport.sent.

To test code that sends mail without building a mailer, use fake(). A FakeMailer has the same send, queue, later, to and raw methods, but records the mailables instead of delivering them.

ts
import { fake } from '@plinthjs/mail'

const mailer = fake()

await mailer.to('ada@example.com').send(new OrderShipped(1))
await mailer.queue(new OrderShipped(2))

mailer.assertSent(OrderShipped)
mailer.assertSent(OrderShipped, (mail) => mail.render().subject === 'Order #1 shipped')
mailer.assertSentCount(1, OrderShipped)
mailer.assertNotSent(Welcome)
mailer.assertQueued(OrderShipped)
mailer.assertNothingQueued() // throws: 1 mailable(s) were: [OrderShipped]

The full set is assertSent, assertNotSent, assertNothingSent, assertSentCount, assertQueued, assertNotQueued and assertNothingQueued. Class arguments are optional, and a predicate receives the mailable instance. The recorded mailables are also available as mailer.sent and mailer.queued.

The fake prepares each mailable before recording it, exactly as the real mailer does (build(), then envelope(), content() and attachments()). The recorded instance therefore already has its subject, recipients and bodies, and mail.toMessage() or mail.render() returns them without any extra step.

Released under the MIT License.