Messaging

Email sending with pluggable backends, sent message storage, and dev-friendly overrides.

Sending email

val result = funktorMessaging.mailing.send(
    Email(
        source = "noreply@example.com",
        destination = EmailDestination.to("user@example.com"),
        subject = "Your order has shipped",
        body = EmailBody.Html {
            body { p { +"Your package is on the way." } }
        },
    )
)

if (result.success) {
    log.info("Sent email: ${result.messageId}")
}

Configuring a sender

Supply your provider and nothing else. Dev overrides, test-mode capture, persisting what was sent and the debug log are applied by the messaging module itself, so there is no chain to assemble and no step to forget.

val blueprint = kontainer {
    funktor(
        config = config,
        messaging = {
            useKarango()                       // persist sent messages

            // The ONE thing the app supplies. Built at most once, and never called at all
            // when the app runs in test mode.
            useSender(devConfig = config.devOverrides?.mailing) {
                AwsSesSender.of(config.aws.ses)
            }

            // Optional: your hooks run alongside the framework's, outside the dev overrides.
            onAfterSend { email, result -> metrics.record(result) }
        },
        // ...
    )
}
Do not register an EmailSender yourself. It is deliberately not a Kontainer service — the provider lives behind useSender so nothing can inject an undecorated sender and bypass the guarantees below. Send through Mailing (funktorMessaging.mailing).

Email senders

Sender Use case
AwsSesSender AWS Simple Email Service. Production-grade delivery.
SendgridSender SendGrid API. Alternative cloud provider.
NullEmailSender No-op. Discards all emails silently.
OverridingEmailSender Wraps another sender and redirects all emails to a dev inbox.

Dev overrides

Pass a MailingDevConfig to useSender and the module redirects every email to your dev inbox, prefixes the subject and adds a banner to the body. No accidental emails to real users.

In production the real sender is used directly. In dev/staging all emails go to the address you configure, with the original recipient recorded in the send result.

Tests capture instead of sending

When ktor.deployment.environment is test, the module replaces your provider with a capturing sender — your useSender lambda is never invoked, so no client is built and no credentials are needed. Assert on what was sent by resolving CapturedEmails:

class MyMailSpec : FunktorApiSpec() {
    private val emails by service(CapturedEmails::class)

    init {
        "a password reset sends a mail with a usable link" {
            // ... trigger the flow ...
            val mail = emails.lastTo("user@example.com").shouldNotBeNull()
            val link = mail.hrefs().single()
        }
    }
}
Read the mail from CapturedEmails, not from SentMessagesStorage: the persisted copy of an auth mail is anonymized, so the token is deliberately gone from it.

Auth email templates

The auth module's three transactional mails — account activation, password changed, password recovery — are rendered in Kotlin, one template class each, selected per locale.

abstract class AccountActivationEmailTemplate :
    LocalizedEmailTemplate<AccountActivationEmailTemplate.Params>() {

    data class Params(
        val recipient: EmailAddress,
        val senderEmail: String,
        val senderName: String,
        val applicationName: String,
        val activationUrl: String,
    )
}

Each template declares its own Params, so a value that is renamed or forgotten is a compile error rather than a placeholder shipped to a recipient. Renderings live in a Map<Locale, (Params, Locale) -> Email>, and a shared walker resolves de-CH → de → en. The renderer is handed the locale it matched, so the map key and the rendering cannot drift apart into a mixed-language mail.

This started out as Markdown templates with {{placeholder}} substitution. It was built, reviewed, and thrown away — the review found a value that could be dropped from the args map and ship a literal placeholder to every recipient with the whole test suite green. Types do not have that failure mode.

Branding

EmailLayout is the chrome around a template's content — colours, header, frame, footer. Supply one and all three mails use it:

val branded = EmailLayout { locale, content ->
    EmailBody.Html {
        body {
            div { +"…header…" }
            content()
            div { +footerFor(locale) }
        }
    }
}

AuthEmailTemplates.default(branded)

The layout receives the locale because a footer carries the imprint and unsubscribe line, and those have to be translated. A layout blind to the locale can only put an English footer under a German body. Replace an individual mail by subclassing its template and passing it alongside the layout.

What templates do not control

A template builds the Email and nothing downstream of it. The caller applies the storing policy and re-asserts the envelope, so a template cannot choose whether its own live token is persisted, nor add a cc that would deliver an activation link to a second mailbox.

Email hooks

Add hooks with onAfterSend in the messaging block. They run in the same place as the framework's own StoringEmailHook — outside the dev overrides, so they see the mail as your app composed it — and they still run under test. A hook buried inside the useSender lambda would do neither.

Sent message storage

Sent emails are persisted to a SentMessagesStorage via the storing hook, for any mail carrying an EmailStoring policy. Mail without one is not stored. Auth mails use withAnonymizedContent, which strips every link so a live token never reaches the database. Query by reference (e.g. user ID) to see what was sent and when. Storage backends: useKarango() for ArangoDB, useMonko() for MongoDB.