Skip to main content

Email notifications

Email notifications tell people about their own access without an admin writing to them by hand. The gateway can email a user when a key is created or rotated for them, when they are invited to the Admin UI, when a budget threshold is crossed, when a key of theirs is about to expire, and when a key of theirs was reported as leaked and blocked. Emails are sent by one of three email loggers, configured as a callback. Each event can be turned on or off from the Admin UI or the API. Email notifications are free on every gateway. Replacing the Spanway logo, support contact and footer with your own needs a Spanway Enterprise license.

A real-world scenario​

A platform admin onboards a new data scientist. She creates a user for them in the Admin UI with an invitation, then a key with their user id. The gateway sends two emails, one with the sign in link and one saying a key was created for them, both without the key value itself. A month later the key crosses its soft budget, and the data scientist gets a budget email before the key is blocked, so they ask for a higher budget in time instead of finding out from a failing script.

Set up a sender in the config file​

  1. Add exactly one email logger to spanway_settings.callbacks, and email to the alerting destinations so the test and the team budget emails go out:

    spanway_settings:
    callbacks: ["smtp_email"]
    general_settings:
    alerting: ["email"]
  2. Set its environment variables and PROXY_BASE_URL, so links in emails point at your gateway, and restart:

    export SMTP_HOST="smtp.example.com"
    export SMTP_PORT="587"
    export SMTP_USERNAME="gateway"
    export SMTP_PASSWORD="..."
    export SMTP_SENDER_EMAIL="gateway@example.com"
    export SMTP_TLS="true"
    export PROXY_BASE_URL="https://gateway.example.com"
    export TEST_EMAIL_ADDRESS="you@example.com"
  3. Send a test email:

    curl "http://localhost:4000/health/services?service=email" \
    -H "Authorization: Bearer $SPANWAY_API_KEY"

    Expected result:

    {"status": "success", "message": "Mock Email Alert sent, verify Email Alert Received"}

    A test key email arrives at TEST_EMAIL_ADDRESS within a minute. Only proxy admins can run the test. It sends through the SMTP variables, not through SendGrid or Resend, so on a SendGrid or Resend gateway check the setup by creating a key for a user with an email address instead. Without email in alerting the test answers 422, and when the send fails it answers 500.

CallbackEnvironment variables
smtp_emailSMTP_HOST, SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD, SMTP_SENDER_EMAIL, SMTP_TLS, SMTP_USE_SSL, SMTP_TIMEOUT
sendgrid_emailSENDGRID_API_KEY, SENDGRID_SENDER_EMAIL
resend_emailRESEND_API_KEY, RESEND_FROM_EMAIL

SMTP_TLS uses STARTTLS on a plain connection and is on by default. SMTP_USE_SSL opens an implicit TLS connection, which most providers expect on port 465, and is off by default but turns itself on when SMTP_PORT is 465. Both accept true, false, 1, 0, yes, no, on or off in any case. SMTP_PORT defaults to 587 and SMTP_TIMEOUT to 30 seconds. Without SMTP_HOST, RESEND_API_KEY or SENDGRID_API_KEY no email is sent at all and the gateway logs a warning.

Set up SMTP from the Admin UI​

  1. Sign in as a proxy admin and open Settings, then Logging & Alerts, then the Email Alerts tab.
  2. In the Email Server Settings card, fill in SMTP_HOST, SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD, SMTP_SENDER_EMAIL and TEST_EMAIL_ADDRESS, and leave SMTP_TLS on unless your server needs otherwise.
  3. Click Save Changes. The page shows "Email settings updated successfully". Only the fields you changed are sent, so a value that comes from the environment is never copied into the database.
  4. Click Test Email Alerts. The page shows "Email test triggered. Check your configured email inbox/logs." and the test email arrives at TEST_EMAIL_ADDRESS.

Events​

EventSent whenDefault
Virtual Key CreatedA key is created for a user with an email address.On
New User InvitationA user is invited, for example with /user/new and send_invite_email: true.On
Virtual Key RotatedA key is regenerated or rotated on schedule.On
Soft Budget CrossedSpend passes a key's soft_budget.On
Max Budget AlertSpend approaches or reaches max_budget.On
Virtual Key ExpiringA key reaches one of the general_settings.key_hygiene.expiry_notice_days thresholds, 30 days and 1 day before its expiry date by default. Needs a license granting key_hygiene, see leaked keys and key expiry.On
Virtual Key CompromisedA key was reported as leaked and blocked, see leaked keys and key expiry.On

Key emails do not contain the key value by default, because an email can be forwarded, archived or read by someone else. Set EMAIL_INCLUDE_API_KEY=true only if your policy allows sending keys by email.

Budget emails can be tuned with three more settings.

SettingDefaultWhat it does
EMAIL_BUDGET_ALERT_MAX_SPEND_ALERT_PERCENTAGE0.8The share of max_budget at which the Max Budget Alert email goes out, so people hear about it before requests are refused.
EMAIL_BUDGET_ALERT_TTL86400Seconds the same budget email stays quiet after it is sent, so one budget does not flood an inbox.
spanway_settings.default_key_max_budget_alert_emails, or max_budget_alert_emails in a key's metadataunsetThresholds with extra recipients, for example {"50": ["finance@example.com"], "90": ["finance@example.com", "lead@example.com"]}, so finance hears at 50% and the team lead at 90%. When set, it replaces the single 80% email.

Turn events on or off​

In the Admin UI, the Email Notifications card on the Email Alerts tab lists every event with a checkbox and a description. Tick or untick events and click Save Changes, which shows "Email event settings updated successfully". Reset to Defaults puts every event back on at once, with no confirmation.

With the API, read the current switches:

curl http://localhost:4000/email/event_settings \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Expected result:

{
"settings": [
{"event": "Virtual Key Created", "enabled": true},
{"event": "New User Invitation", "enabled": true},
{"event": "Virtual Key Rotated", "enabled": true},
{"event": "Soft Budget Crossed", "enabled": true},
{"event": "Max Budget Alert", "enabled": true},
{"event": "Virtual Key Expiring", "enabled": true},
{"event": "Virtual Key Compromised", "enabled": true}
]
}

Change the events you name and leave the rest as they are:

curl -X PATCH http://localhost:4000/email/event_settings \
-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
-d '{"settings": [{"event": "Virtual Key Created", "enabled": true}, {"event": "Soft Budget Crossed", "enabled": false}]}'

Expected result:

{"message": "Email event settings updated successfully"}

POST /email/event_settings/reset turns every event back on and answers {"message": "Email event settings reset to defaults"}. Reading needs a proxy admin or admin viewer, and writing needs a proxy admin. Every change is written to the audit log with the switches before and after, and it applies at once on every gateway replica.

MethodPathSummary
GET/email/event_settingsList the email events and whether each one is on
PATCH/email/event_settingsTurn email events on or off
POST/email/event_settings/resetTurn every email event back on

Branding​

With a license, EMAIL_LOGO_URL, EMAIL_SUPPORT_CONTACT and EMAIL_SIGNATURE replace the Spanway logo, the support contact and the footer in every email, including the team budget emails sent by the email alerting destination, where SMTP_SENDER_LOGO also sets the logo. Without a license these variables are ignored, a warning is logged and the defaults are used. In the Admin UI the two licensed fields on the Email Server Settings card are disabled without a license.

Also with a license, four variables replace the subject line of one event each, which helps when your mail filters or your users expect your own wording. Without them, the subject is Spanway: followed by the event's message, for example Spanway: Your API key expires in 5 days. Without a license they are ignored like the branding variables.

VariableEventDefault subject
EMAIL_SUBJECT_KEY_EXPIRINGVirtual Key ExpiringSpanway: Your API key expires in <days>
EMAIL_SUBJECT_KEY_COMPROMISEDVirtual Key CompromisedSpanway: Your API key was reported as leaked and blocked
EMAIL_SUBJECT_KEY_CREATEDVirtual Key CreatedSpanway: followed by the key created message
EMAIL_SUBJECT_INVITATIONNew User InvitationSpanway: followed by the invitation message

The variable is used as the whole subject, so a custom expiry subject does not show the days left. The days stay in the body of the email.

Access request decisions are emailed to the requester through the same logger, see access requests. Slack, webhook and other alert channels are described in alerting.

Errors​

StatusWhereMeaningFix
403GET /email/event_settingsThe caller is neither a proxy admin nor an admin viewer.Use an admin key.
403PATCH /email/event_settings, POST /email/event_settings/resetThe caller is not a proxy admin. Admin viewers can read but not change the switches.Sign in as a proxy admin.
400 general_settings key 'email_settings' is set in the config file and cannot be changed here. with a resolution fieldPATCH and POST above, and Save Changes in the Admin UIemail_settings is fixed in the config file, and the database may not override it.Change it in the config file, or remove it from there to manage it here.
422PATCH /email/event_settingsThe body is not a list of {"event", "enabled"} pairs, or an event name is not one of the seven in the table above.Use the exact event names, for example Soft Budget Crossed.
500 Database not connected. Set DATABASE_URL to manage email event settingsEvery /email routeThe gateway runs without a database, so there is nowhere to store the switches.Set DATABASE_URL.
422 "email" not in proxy config: general_settings. Unable to test this.GET /health/services?service=emailemail is not in general_settings.alerting.Add it to alerting.
500 The test email could not be sent. The gateway log has the cause.GET /health/services?service=emailThe send failed, for example SMTP refused the login or TEST_EMAIL_ADDRESS is unset.Look for Error sending email alert or Failed to send email alert in the gateway log.
403 Only proxy admins can trigger the email test alert.GET /health/services?service=emailThe test sends a real email.Sign in as a proxy admin.
Test email never arrives after a 200GET /health/services?service=emailThe provider accepted and then dropped the message, for example as spam.Check the provider's activity log and the spam folder.

Logs​

LevelLineMeaning
WARNINGRESEND_API_KEY is not set, Resend emails will be rejectedThe resend_email logger is configured without its key. Set the variable.
WARNINGNo email provider configured (set SMTP_HOST, RESEND_API_KEY or SENDGRID_API_KEY), dropping email '<subject>' from <sender> to <recipients>An email was due but no provider is set up, so it was not sent. Set one of the variables.
WARNINGMax budget alert at <n>% has no recipients, skippingA budget threshold was crossed but the key or team has no owner with an email address. Give the key an owner.
WARNINGIgnoring non-numeric max budget alert threshold ...A threshold in the budget alert settings is not a number. Fix the setting.
ERRORFailed to send email alert <key>: <error>The provider rejected the message. The error is the provider's answer, usually bad credentials, a rejected sender address or a closed port.
WARNINGIgnoring malformed general_settings.email_settings: ...The stored switches could not be read, so the defaults are used. Save the switches again from the Admin UI.
WARNING<variable> is set but email customization requires an enterprise license, using the defaultA branding variable is set on a gateway without a license. Add a license or remove the variable.
ERRORTrying to send email alert to no recipientAn alert email had nobody to go to. Give the key or user an email address.