Web & UI/Emails & Mailers

Emails & Mailers

Crest email templates, mail.RenderHTML, attachments, delivery error semantics, providers, and dev preview.

github.com/fletchhq/fletch/mail· fletch docs show emails-and-mailers

On this page

The github.com/fletchhq/fletch/mail package defines a provider-independent Mailer interface, renders Crest components to HTML, classifies transport failures for safe retries, and includes an in-memory outbox wired into the dev dashboard.

Messages and attachments

Build outbound emails with mail.Message and mail.Attachment:

type Message struct {
	From        string
	To          []string
	CC          []string
	BCC         []string
	Subject     string
	Text        string
	HTML        string
	Headers     map[string]string
	Attachments []Attachment
}

type Attachment struct {
	Filename    string
	ContentType string
	Data        []byte
}

Attachment.MediaType() returns the normalized media type for the attachment. Call msg.Validate() before sending (providers call it too). An invalid message returns an error matching errors.Is(err, mail.ErrInvalidMessage).

The mail.Mailer interface

Every email backend implements mail.Mailer:

type Mailer interface {
	Send(ctx context.Context, m Message) error
	Describe() Description
}

Wire the configured backend into your application in bootstrap/app.go with fletch.WithMailer(m):

app := fletch.New(
	fletch.WithMailer(mailer),
)

Crest email templates in ui/emails/

Scaffold an email template with the CLI:

fletch make email welcome

This creates ui/emails/welcome.go and ui/emails/welcome.crest. If ui/emails/layout.go and ui/emails/layout.crest do not exist yet, the generator creates them too.

Every compiled Crest component implements mail.Component structurally without importing mail:

type Component interface {
	Render(ctx context.Context, w io.Writer) error
}

Render a Crest email component into Message.HTML with mail.RenderHTML(ctx, c) (string, error), and provide a plain-text fallback in Message.Text.

The generated Welcome props have Subject and Name. Add the fields your template needs, such as a dashboard link, in ui/emails/welcome.go:

package emails

type Welcome struct {
	Subject      string
	Name         string
	DashboardURL string
}

The template lives in the same emails package as the layout, so it refers to it as <Layout>, and reads props through the receiver w (from Welcome):

<!-- ui/emails/welcome.crest -->
<Layout title={w.Subject}>
  <h1 style="margin:0 0 16px;font-size:22px;">Welcome, {w.Name}</h1>
  <p>Your account is ready. Your starter guide is attached.</p>
  <p><a href={w.DashboardURL}>Open your dashboard</a></p>
</Layout>

Run fletch gen after editing the template.

Keep template rendering and message construction in an application mailer/ package so handlers and jobs call typed methods:

package mailer

import (
	"context"
	"fmt"

	"github.com/fletchhq/fletch/mail"
	"myapp/ui/emails"
)

type AppMailer struct {
	transport mail.Mailer
	from      string
}

func New(transport mail.Mailer, from string) *AppMailer {
	return &AppMailer{transport: transport, from: from}
}

func (m *AppMailer) SendWelcome(ctx context.Context, to, name, dashboardURL string, guidePDF []byte) error {
	html, err := mail.RenderHTML(ctx, emails.Welcome{
		Subject:      "Welcome to MyApp",
		Name:         name,
		DashboardURL: dashboardURL,
	})
	if err != nil {
		return err
	}

	msg := mail.Message{
		From:    m.from,
		To:      []string{to},
		Subject: "Welcome to MyApp",
		HTML:    html,
		Text:    fmt.Sprintf("Welcome, %s.\n\nOpen your dashboard: %s\n", name, dashboardURL),
		Attachments: []mail.Attachment{
			{
				Filename:    "getting-started.pdf",
				ContentType: "application/pdf",
				Data:        guidePDF,
			},
		},
	}

	return m.transport.Send(ctx, msg)
}

For user-facing HTTP routes, enqueue a Quiver background job that calls AppMailer.SendWelcome instead of waiting on SMTP or third-party HTTP APIs during the request.

Delivery error semantics and retries

Network failures during email delivery fall into two categories with different retry rules:

Outcome Sentinel / Helper Meaning Retry guidance
mail.DeliveryNotSent errors.Is(err, mail.ErrNotSent) / mail.NotSent(err) The transport never accepted the message (connection refused, DNS error, auth failure, 4xx rejection). Safe to retry automatically without risking duplicate email.
mail.DeliveryUncertain mail.Uncertain(err) The request was written to the transport and the connection dropped or timed out before a response arrived. Retrying may send a duplicate. Log, alert, or check provider state before resending.

Transport adapters wrap errors in *mail.DeliveryError using mail.NotSent(err), mail.Uncertain(err), and mail.HTTPError(err). Inspect the error in your job worker so uncertain deliveries are not blindly retried:

err := w.mailer.SendWelcome(ctx, job.Args.To, job.Args.Name, job.Args.DashboardURL, pdf)
if err != nil {
	if errors.Is(err, mail.ErrNotSent) {
		return err // safe for Quiver to retry with backoff
	}
	var derr *mail.DeliveryError
	if errors.As(err, &derr) {
		w.log.Warn("mail delivery outcome uncertain; skipping auto-retry", "err", derr)
		return quiver.Discard(err)
	}
	return err
}

Providers

SMTP is built directly into the core github.com/fletchhq/fletch/mail package. There is no mail/smtp submodule. Hosted API providers live in standalone submodules so apps only pull the SDK dependencies they actually use.

Provider Import path Constructor
SMTP github.com/fletchhq/fletch/mail mail.SMTP(mail.SMTPConfig{...})
Resend github.com/fletchhq/fletch/mail/resend resend.New(...)
Postmark github.com/fletchhq/fletch/mail/postmark postmark.New(...)
Amazon SES github.com/fletchhq/fletch/mail/ses ses.New(...)

Core SMTP

mail.SMTP connects on Send rather than holding idle sockets open. Port defaults to 587 (STARTTLS), or 465 when ImplicitTLS is true.

m := mail.SMTP(mail.SMTPConfig{
	Host:        cfg.SMTPHost,
	Port:        587,
	Username:    cfg.SMTPUser,
	Password:    cfg.SMTPPass,
	ImplicitTLS: false,
	RequireTLS:  true,
	Timeout:     10 * time.Second,
	TLSConfig:   nil,
})

Resend

import "github.com/fletchhq/fletch/mail/resend"

m := resend.New(
	resend.APIKey(cfg.ResendAPIKey),
	// Optional overrides:
	// resend.Endpoint("https://api.resend.com"),
	// resend.HTTPClient(customHTTPClient),
)

Postmark

import "github.com/fletchhq/fletch/mail/postmark"

m := postmark.New(
	postmark.Token(cfg.PostmarkToken),
	postmark.MessageStream("outbound"),
	// Optional overrides:
	// postmark.Endpoint("https://api.postmarkapp.com"),
	// postmark.HTTPClient(customHTTPClient),
)

Amazon SES

import "github.com/fletchhq/fletch/mail/ses"

m := ses.New(
	ses.Region("us-east-1"),
	ses.WithCredentialsProvider(ses.DefaultCredentials()),
	ses.ConfigurationSet("transactional"),
)

The mail/ses package provides composable credential helpers for local dev, ECS, and EC2:

  • ses.DefaultCredentials()
  • ses.ChainCredentials(...)
  • ses.EnvCredentials()
  • ses.ContainerCredentials(...)
  • ses.IMDSCredentials(...)
  • ses.CachedCredentials(...)
  • ses.StaticCredentials(...)

Use ses.Credentials(...) to pass static credentials directly or ses.WithCredentialsProvider(...) to pass a provider chain.

Development preview and testing

In-memory mail.Outbox

In development and tests, mail.Outbox() captures every sent message in memory instead of delivering it over the network:

outbox := mail.Outbox()
app := fletch.New(fletch.WithMailer(outbox))

Outbox exposes inspection and lifecycle methods for assertions and custom dev tooling:

Method Purpose
Messages() Returns captured mail.Message values.
Entries() Returns captured entries with IDs and metadata.
Entry(id) Looks up a single captured entry by ID.
Delete(id) Removes one entry from the outbox.
Reset() Clears all captured messages (useful between tests).
Changed() Signals when the outbox contents change (used for live UI updates).
Handler() Returns an http.Handler serving the outbox UI/API (also available via mail.DevHandler(o)).

Dev Dashboard Mail tab

When running fletch dev with mail.Outbox(), the Dev Dashboard (http://127.0.0.1:4000) automatically displays captured emails in its Mail tab. Each message includes:

  • Sandboxed HTML preview with Desktop and Mobile (375px) viewport toggles
  • Plain-text body tab
  • Headers view
  • Raw message source
  • Attachments list with download links

Contract tests for custom mailers

If you implement a custom mail.Mailer adapter, run the built-in contract suite from github.com/fletchhq/fletch/mail/mailtest in your test file:

package mymailer_test

import (
	"testing"

	"github.com/fletchhq/fletch/mail"
	"github.com/fletchhq/fletch/mail/mailtest"
)

func TestMailerContract(t *testing.T) {
	mailtest.Run(t, func(t *testing.T) mail.Mailer {
		return newTestMailer(t)
	})
}