Mail and SMS

This page explains how Behemoth sends email and text messages, what you provide, and what to expect when a send is slow or fails. Read Plugins and hooks first.

Behemoth sends nothing itself. It has no mail or SMS provider, and it writes no message text. You give it a sender at Boot, and every plugin that needs to send a message goes through it. You keep your provider, your templates, and your languages.

Which plugins send messages #

Only some plugins send messages. If you use none of them, you do not need a sender:

PluginSendsBy
Magic linkA sign-in linkMail
Email verificationA link that confirms an address, and email change messagesMail
Email and password, with password reset onA reset link, and a notice that the password changedMail
Phone numberA one-time code to verify a number, to sign in, or to reset a passwordSMS
Two-factorA setup message and a sign-in code, for users who choose email or text message as their second factorMail or SMS

If a plugin needs a sender and you did not set one, Boot fails with a configuration error. You find the problem at startup, not when the first user asks for a link.

Give Behemoth a sender #

A sender is a function that takes a message and delivers it. Pass one for each channel you use:

go
ac, err := engine.Boot(
    ctx,
    app,
    db,
    engine.BootConfig{
        Crypto: cryptoCfg,
        Mail: core.MailConfig{
            Sender: core.MailSenderFunc(sendMail),
        },
        SMS: core.SMSConfig{
            Sender: core.SMSSenderFunc(sendText),
        },
    },
)
if err != nil {
    log.Fatal(err)
}

func sendMail(ctx context.Context, msg core.MailMessage) error {
    locale, _ := msg.Metadata["locale"].(string)
    switch msg.Kind {
    case core.MailMagicLink:
        return mailQueue.Enqueue(
            ctx,
            msg.To,
            templates.SignIn(locale),
            msg.URL,
        )
    case core.MailEmailVerification:
        return mailQueue.Enqueue(
            ctx,
            msg.To,
            templates.Verify(locale),
            msg.URL,
        )
    }
    return fmt.Errorf("no template for mail kind %q", msg.Kind)
}

func sendText(ctx context.Context, msg core.SMSMessage) error {
    return provider.Send(ctx, msg.To, textFor(msg.Kind, msg.Code))
}

In this example, mailQueue, templates, provider, and textFor belong to your application. Return an error when the message was not delivered or handed off. Your provider's API key belongs to your sender and is not part of the configuration.

The message #

Pick the subject and the template by the message's Kind. A mail message carries these fields:

FieldContent
KindWhat the message is for, such as core.MailMagicLink, core.MailEmailVerification, or core.MailPasswordReset
ToThe address, trimmed and lowercased
URLThe link to put in the message, with the token in it
CodeFor a kind that carries a code instead of a link, the code for the person to type
ExpiresAtWhen the link or the code stops working
UserThe user the message is about
MetadataWhat the request carried under metadata, such as a locale or a template name

An SMS message has Kind, To (a number in E.164 form), Code, ExpiresAt, User, and Metadata. The Mail and SMS references list every kind.

Treat tokens, codes, and metadata with care

A link, a token, and a code are credentials. Do not write them to your logs. Metadata is input from the client, which Behemoth passes through without reading it. Check a value before you use it in a template or a query.

Waiting and background sends #

A plugin hands a message to your sender in one of two ways. Each plugin picks the one that suits the operation:

The request waitsIn the background
The request returnsAfter your sender doesOnce the message is queued
A failed sendIs returned to the plugin, which can act on it. For example, a magic link is revoked.Is logged and counted. Nobody is told.
Used byMagic links, password reset links, phone number codes, and two-factor codes, when you set WaitForSend. The notice of an email change always waits, because the change does not start without it.Email verification links, the notice that a password changed, and all of the others by default

Email verification sends in the background because nothing is lost when a send fails: the user asks for another link. A sign-up should not wait for a mail provider.

Set WaitForSend only when your sender is fast, for example when it puts the message on a queue. For a magic link, the sender runs only for an address that has an account. A slow sender then makes that request slower than one for an unknown address, and the difference shows which addresses are registered.

The background queue #

Background sends run on a small pool inside Behemoth. MailConfig and SMSConfig have the same three settings:

FieldDefaultMeaning
Workers4How many sends run at once.
QueueSize256How many messages may wait. When the queue is full, a new message is refused, and the plugin treats that as a failed send.
SendTimeout30 secondsHow long one background send may take.
The queue is in memory and does not retry

A message that fails is gone, and messages that are still waiting are lost if the process stops without Close. If you need retries or durable delivery, make your sender put the message on your own queue or outbox and return at once. Both modes are then fast and nothing is lost.

At shutdown, call ac.Mailer.Close(ctx) and ac.SMS.Close(ctx). Each stops accepting messages and waits for the queued ones, or for the context to end. Mail and SMS have separate queues. See Shut down cleanly.

Develop without a provider #

In development, a sender can print the link to your terminal, so you can follow a magic link without sending mail. Never do this in production, because the link signs the user in.

Codes and links #

Mail usually carries a link, and an SMS carries a code. They are different credentials:

Link tokenOne-time code
SecretA long random string4 to 12 digits, 6 by default
TravelsIn a linkTyped by a person
GuessingNot feasibleBounded by a number of attempts, 5 by default
LifetimeSet per kind of token5 minutes by default
Live at onceAny number per userOne per kind and subject. A new code replaces the old one.
Managed byac.TokenManagerac.Codes

A wrong, expired, used, or exhausted code all return the same error, code_invalid, so a client learns nothing about why a guess failed. Behemoth stores only a keyed hash of a code. See Credentials.

Send from your own plugin #

A plugin takes the mailer from the AuthContext it receives in Init. Define your own core.MailKind for a message of your own, and document it so the application can add a template for it.

go
msg := core.MailMessage{
    Kind: "myplugin.invite",
    To:   email,
    URL:  link,
}

// Waits for the sender and returns its error.
if err := ac.Mailer.Send(ctx, msg); err != nil {
    return err
}

// Returns once the message is queued.
if err := ac.Mailer.SendAsync(ctx, msg); err != nil {
    return err
}

Use Send when your code does something about a failure. Use SendAsync when a failed send costs the user a retry and nothing else. The error that SendAsync returns means the message was not queued. To fail early, check ac.Mailer.Configured() in Init. ac.SMS works the same way.

Metrics #

Behemoth counts messages in behemoth.mail.sent and behemoth.sms.sent, by kind and result. The result is sent, error when your sender returned an error, or dropped when the background queue was full. Alert on dropped and error, because a background failure is otherwise silent. See Telemetry.

Next steps #

To go deeper, read the following pages:

  • Mail: Every message kind and field.
  • SMS: The SMS message, the queue, and one-time codes.
  • Magic link: The link flow and the WaitForSend option.
  • Phone number: Sign-in and verification with a code.