Runbook — Keycloak realm SMTP (transactional email)
How a new OpenGov instance gets working transactional email — the mail
Keycloak sends for password reset, email verification, and “update email”
flows. This is realm-level SMTP, configured independently for opengov and opengov-applicants from the same protected deployment settings.
Scope: this is Keycloak’s email path only. The OpenGov application’s own applicant/role notifications are a separate, not-yet-wired surface (a SmartLink connector +
notification_providersrow, with a still-stubbed send adapter). Configuring the values here does not enable app notifications.
How it’s provisioned (config-as-code)
The compose init service (opengov.bootstrap_deployment) configures realm SMTP
on every boot via configure_keycloak_smtp(); bootstrap_applicant_realm() applies it to the applicant realm as well. No staff account is seeded into that realm. Both realms are present by default, with public registration closed. Opening applicant registration additionally requires Keycloak’s successful SMTP connection test; see the applicant runbook. It is:
- Opt-in — runs only when both
OPENGOV_SMTP_HOSTandOPENGOV_SMTP_FROMare set. A deployment without a mail relay boots clean; KC just can’t send mail. - Idempotent — a realm-scoped
PUT /admin/realms/<realm>carrying onlysmtpServerreplaces just the SMTP config (KC leaves other realm fields untouched), so it converges on every restart. It does not rely on the realm-import JSON, which is skipped (HTTP 409) on an already-imported realm. - Non-fatal — an SMTP hiccup is logged and swallowed; only the deployments-row seed is a hard boot gate.
auth is derived automatically: enabled only when both OPENGOV_SMTP_USER and
OPENGOV_SMTP_PASSWORD are present.
Environment variables
Set these on the deployment (Coolify env / .env). They are bootstrap-only
and scoped to the init service — do not add them to the app/worker services
(Settings uses extra='forbid'; an undeclared OPENGOV_ var crashes boot).
| Var | Required | Default | Notes |
|---|---|---|---|
OPENGOV_SMTP_HOST | ✅ (to enable) | — | e.g. smtp-relay.brevo.com |
OPENGOV_SMTP_FROM | ✅ (to enable) | — | must be a verified sender/domain at the relay |
OPENGOV_SMTP_PORT | 587 | 587 = STARTTLS, 465 = implicit SSL | |
OPENGOV_SMTP_FROM_DISPLAY | OpenGov | display name | |
OPENGOV_SMTP_USER | — | relay login | |
OPENGOV_SMTP_PASSWORD | — | secret — set in the secret store, never commit | |
OPENGOV_SMTP_STARTTLS | true | use with port 587 | |
OPENGOV_SMTP_SSL | false | set true (and starttls false) for port 465 | |
OPENGOV_SMTP_REPLY_TO | — | optional |
Example — Brevo (Sendinblue) relay
OPENGOV_SMTP_HOST=smtp-relay.brevo.com
OPENGOV_SMTP_PORT=587
OPENGOV_SMTP_STARTTLS=true
OPENGOV_SMTP_SSL=false
OPENGOV_SMTP_FROM=noreply@services.example.gov
OPENGOV_SMTP_FROM_DISPLAY=OpenGov
OPENGOV_SMTP_USER=<the SMTP login, e.g. 9d8f50001@smtp-brevo.com>
OPENGOV_SMTP_PASSWORD=<the SMTP key — NOT the account password>
Brevo gotchas:
- The SMTP key (SMTP & API → SMTP tab) is not your account password and
not an API key. Using the wrong one gives
535 authentication failed. OPENGOV_SMTP_FROMmust be a verified sender (Senders & Domains) or Brevo rejects the message at send time even though config saves fine.- Free tier caps at 300 emails/day.
Verifying
After deploy, confirm the realm got the config (any host with DB access):
docker exec <postgres-container> psql -U opengov -d opengov -tAc \
"SELECT s.name, CASE WHEN s.name='password' THEN '***' ELSE s.value END \
FROM realm_smtp_config s JOIN realm r ON r.id=s.realm_id \
WHERE r.name='opengov' ORDER BY s.name;"
Validate the relay credentials + egress directly (run from the deployment host so it also proves the network path KC uses):
printf 'machine %s login %s password %s\n' smtp-relay.brevo.com "$USER_LOGIN" "$SMTP_KEY" > /tmp/nr && chmod 600 /tmp/nr
curl -sS --ssl-reqd --url "smtp://smtp-relay.brevo.com:587" --netrc-file /tmp/nr \
--mail-from "$FROM" --mail-rcpt "you@example.com" \
--upload-file <(printf 'From: %s\nTo: you@example.com\nSubject: smtp test\n\nhi\n' "$FROM") -v
rm -f /tmp/nr
235 = auth ok; 250 ... queued after DATA = sender accepted and message
queued. 535 = bad login/key; 550 at MAIL FROM = sender not verified.
Don’t rely on Keycloak’s console “Test connection” button as the sole check — it sends to the logged-in admin’s email, and the master
adminuser has no email, so it fails unhelpfully. Thecurlpath above exercises the identical host/port/STARTTLS/auth/from tuple KC uses.
Rotating the secret
Generate a new key at the relay, update OPENGOV_SMTP_PASSWORD in the secret
store, redeploy (the idempotent init step re-applies it). Revoke the old key.
Note: KC stores the password in realm_smtp_config in plaintext (no vault
configured), so treat the DB and any transcript that carried the key as sensitive.
Example — Amazon SES
Amazon SES (Simple Email Service) is the mail relay of Amazon Web Services (AWS). Use it when the deployment already runs on AWS. The sections “Environment variables”, “Verifying” and “Rotating the secret” apply to SES too.
SES differs from Brevo in four ways:
- The sender must be a verified SES identity in the same region as the relay.
- The SMTP user is the access key ID of an IAM user. IAM (Identity and Access Management) is the AWS service that holds users and their permissions.
- The SMTP password is not the secret access key. You derive it from the secret access key.
- The SMTP password works in one region only.
Steps
- Choose one region. Use the same region in every step.
- Request production access for that region. A new SES account starts in the SES sandbox. This AWS limit lets it send only to verified addresses. It is not the OpenGov sandbox.
- Create a domain identity for the sender domain. Turn on Easy DKIM. DKIM is a signature that the sender adds to each mail. The receiver uses it to verify the mail.
- Add the three CNAME records that SES displays to the DNS zone of the domain.
- Wait until the DKIM status is
SUCCESS. The console displays “Successful”. This can take up to 72 hours. - Create an IAM user for the deployment. Attach the policy below. Do not use a root key or a personal key.
- Create one access key for the IAM user. AWS displays the secret access key one time.
- Derive the SMTP password with the script below. Do not paste the secret access key into a chat or a ticket.
- Store the SMTP password in the secret store at once. Then discard the secret access key.
- Run the
curlprobe from “Verifying” with the SES host, the access key ID and the SMTP password. SES must answer235. - Set the variables below and deploy.
- Run the realm query from “Verifying”. Then request one “Forgot password” mail for a user that has a real email address.
The policy lets the IAM user send mail from the sender domain and from no other domain:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "ses:SendRawEmail",
"Resource": "arn:aws:ses:<region>:<account-id>:identity/<domain>",
"Condition": {"StringLike": {"ses:FromAddress": "*@<domain>"}}
}]
}
The script derives the SMTP password. It reads two variables. Use these names. Do not use
AWS_SECRET_ACCESS_KEY, because an AWS profile can already set it. The script stops with
an error when a variable is not set.
import base64
import hashlib
import hmac
import os
def sign(key, message):
return hmac.new(key, message.encode(), hashlib.sha256).digest()
region = os.environ["SES_REGION"] # the region of the SES identity, for example eu-west-1
secret = os.environ["SES_IAM_SECRET"] # the secret access key of the IAM user
signature = sign(("AWS4" + secret).encode(), "11111111")
for part in (region, "ses", "aws4_request", "SendRawEmail"):
signature = sign(signature, part)
print(base64.b64encode(bytes([0x04]) + signature).decode())
Read the secret access key without an echo. Save the script as derive_ses_password.py
and run it:
read -rs SES_IAM_SECRET # paste the secret access key, then press Enter
export SES_IAM_SECRET SES_REGION=eu-west-1
python3 -I derive_ses_password.py
unset SES_IAM_SECRET
The variables:
OPENGOV_SMTP_HOST=email-smtp.<region>.amazonaws.com
OPENGOV_SMTP_PORT=587
OPENGOV_SMTP_STARTTLS=true
OPENGOV_SMTP_SSL=false
OPENGOV_SMTP_FROM=noreply@<domain>
OPENGOV_SMTP_FROM_DISPLAY=OpenGov
OPENGOV_SMTP_USER=<the access key ID, 20 characters>
OPENGOV_SMTP_PASSWORD=<the derived value, 44 characters>
A wrong length means a wrong value. The 44-character value is the output of the script, not the secret access key.
Why the domain needs DKIM
A domain can publish a DMARC policy such as p=quarantine. DMARC is a DNS rule that tells
receivers what to do with mail that has no valid signature. A receiver then puts
unsigned mail from that domain in the spam folder. The domain identity of step 3 signs
each mail, so the mail passes.
SES replies
SES gives 554 for an unverified sender. It does not give the 550 that the section
“Verifying” lists.
| SMTP reply | Cause |
|---|---|
535 Authentication Credentials Invalid | The password is the secret access key. Or the SMTP user is the IAM user name and not the access key ID. Or the region of the password differs from the region of the host. Or the access key is Inactive or deleted. |
554 Message rejected: Email address is not verified | The sender is not an SES identity in this region. Or the SES sandbox is on and the recipient is not verified. |
554 with ses:SendRawEmail in the text | The IAM policy does not allow the call. The sender address, the region or the account ID in the Resource line can be wrong. Or the user has no policy. |
Rotating the SES key
IAM allows two access keys for one user.
- Create a second access key.
- Derive the SMTP password of the second key.
- Run the
curlprobe from “Verifying” with the second key, before the deploy. SES must answer235. - Set
OPENGOV_SMTP_USERandOPENGOV_SMTP_PASSWORDto the new values. Then deploy. - Run the realm query from “Verifying”. Then request one “Forgot password” mail.
- Set the first access key to Inactive. Wait one day. Then delete the first access key.
The boot step does not stop on an SMTP error. A wrong password therefore deploys without an error. If mail stops after step 6, set the first access key to Active again.
Shared account
SES counts bounces and complaints for the whole AWS account in each region. A deployment that sends to wrong addresses can lower the sending reputation of every live service in the same account and region. SES can pause the sending of the whole account.
To limit the risk:
- Send test mail only to addresses that you own.
- Keep applicant registration closed until a test mail arrives. See
applicant-realm.md. - Create a CloudWatch alarm on the SES metrics
Reputation.BounceRateandReputation.ComplaintRate.