Subscribe
AWS

Sending Ghost emails through Amazon SES SMTP with Terraform

My Mailgun login stopped working right after I moved my blog to Ghost 6, and Ghost 6 needs email to let staff log in. Here is how I set up Amazon SES with Terraform, added the DNS records at GoDaddy and pointed Ghost at the SES SMTP endpoint.

Sending Ghost emails through Amazon SES SMTP with Terraform

This month I moved fenixara.com off a hand-built 2020 server onto Docker Compose with Ghost 6. The old setup sent mail through Mailgun over SMTP. I carried the same credentials over, started the new stack, and went to log in to Ghost admin.

I couldn't.

Ghost 6 has a feature called staff device verification. When a staff user signs in from a device Ghost hasn't seen before, it emails a code and waits for you to type it in. My mail wasn't going anywhere, so the code never came. The Ghost logs showed the reason pretty quickly.

Error: Invalid login: 535 Authentication failed
code: 'EAUTH'

The Mailgun credentials were just not valid anymore. I don't know when that happened, the old blog had no reason to send many mails, so nobody noticed. In this blog we will look at how I got back in and then moved Ghost's mail to Amazon SES, with the SES side in Terraform.

Getting back into Ghost admin first

Device verification is a config setting, so you can turn it off for a while. In my compose.yml it comes from the environment.

services:
  ghost:
    environment:
      # Ghost 6 emails a code to staff signing in from a new device. Needs working mail.
      security__staffDeviceVerification: ${GHOST_STAFF_DEVICE_VERIFICATION:-true}

I set GHOST_STAFF_DEVICE_VERIFICATION=false in .env file on the host and recreated the container.

cd /opt/ghost
docker compose up -d ghost

That let me log in with only the password. It's a hole though, so it has to go back on as soon as mail works. Not something to leave for later.

Why SES

I could have fixed the Mailgun account. But everything else for the blog already lives in one AWS account, and I was putting that account into Terraform anyway. SES for a personal blog is basically free. List price is $0.10 per 1000 emails. My account is an old one with no SES free tier, and even then the bill is a rounding error for a blog that sends login codes, invites and the odd password reset.

The domain identity

Ghost sends from an address on my domain, so SES needs to verify the whole domain. The aws_sesv2_email_identity resource does that. With the dkim_signing_attributes block you get Easy DKIM, where SES makes the keys and gives you three tokens to publish as CNAME records.

resource "aws_sesv2_email_identity" "blog" {
  email_identity = "example.com"

  dkim_signing_attributes {
    next_signing_key_length = "RSA_2048_BIT"
  }
}

# Custom MAIL FROM so SPF aligns with the domain (helps DMARC).
resource "aws_sesv2_email_identity_mail_from_attributes" "blog" {
  email_identity         = aws_sesv2_email_identity.blog.email_identity
  mail_from_domain       = "mail.example.com"
  behavior_on_mx_failure = "USE_DEFAULT_VALUE"
}

The second resource is the custom MAIL FROM domain. Without it, the envelope sender is an amazonses.com address, so SPF passes for Amazon's domain and not yours. DMARC wants SPF or DKIM to line up with the From domain. DKIM alone is enough for that, but I wanted both, and it costs two DNS records.

USE_DEFAULT_VALUE means that if SES can't find the MX record on mail.example.com, it falls back to its own domain instead of rejecting the mail. That felt like the safer choice while DNS was still settling.

DNS records at GoDaddy

My DNS isn't in Route 53. It's at GoDaddy, where the domain was bought years ago, and I didn't want to move nameservers in the middle of a migration. So Terraform can't create the records. What it can do is print them.

variable "region" {
  type    = string
  default = "ap-south-1"
}

locals {
  ses_dns_records = concat(
    [for t in aws_sesv2_email_identity.blog.dkim_signing_attributes[0].tokens : {
      type  = "CNAME"
      name  = "${t}._domainkey"
      value = "${t}.dkim.amazonses.com"
    }],
    [
      { type = "MX", name = "mail", value = "10 feedback-smtp.${var.region}.amazonses.com" },
      { type = "TXT", name = "mail", value = "v=spf1 include:amazonses.com ~all" },
      { type = "TXT", name = "_dmarc", value = "v=DMARC1; p=none" },
    ]
  )
}

output "ses_dns_records" {
  description = "Add these at the registrar (names are relative to the domain)"
  value       = local.ses_dns_records
}

output "ses_smtp_host" {
  value = "email-smtp.${var.region}.amazonaws.com"
}

After the apply I printed the output and typed each record into the GoDaddy DNS page by hand.

terraform output -json ses_dns_records | jq -r '.[] | "\(.type)\t\(.name)\t\(.value)"'

Six records, so typing them by hand is fine. One thing to watch: GoDaddy wants the name relative to the domain, so _dmarc and not _dmarc.example.com. That's why the output uses short names. The DMARC policy is p=none for now. It only asks for reports, it doesn't block anything. I'll tighten it once I've watched it for a while.

Then you wait. DKIM verification isn't instant, SES has to see the records first. You can check from the CLI.

aws sesv2 get-email-identity --email-identity example.com \
  --query '{verified: VerifiedForSendingStatus, dkim: DkimAttributes.Status, mailFrom: MailFromAttributes.MailFromDomainStatus}'

When dkim and mailFrom both say SUCCESS, the domain is good.

An IAM user that can only send

SES SMTP logs in with credentials that come from an IAM user's access key. I made a user that can do one thing: send raw email, and only from addresses on my domain.

resource "aws_iam_user" "ghost_ses_smtp" {
  name = "ghost-ses-smtp"
}

resource "aws_iam_user_policy" "ghost_ses_smtp" {
  name = "ses-send-only"
  user = aws_iam_user.ghost_ses_smtp.name
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = ["ses:SendRawEmail"]
      Resource = "*"
      Condition = {
        StringLike = {
          "ses:FromAddress" = "*@example.com"
        }
      }
    }]
  })
}

SMTP sends go through SendRawEmail, so that one action is enough. If the key ever leaks, the worst someone can do is send mail as my domain. Bad, but not "someone deleted my server" bad.

Notice there's no aws_iam_access_key here. That's on purpose. Terraform stores the secret of an access key in state, and I don't want a secret in state. The key is made by a small script outside Terraform. The SMTP password is not the secret key itself, it's derived from it, and I wrote a separate post on deriving an SES SMTP password from an IAM access key in Python.

Pointing Ghost at SES

Ghost takes its mail config from environment variables with double underscores. This is the part of my compose.yml for it.

services:
  ghost:
    environment:
      mail__transport: SMTP
      mail__from: ${MAIL_FROM}
      mail__options__host: ${MAIL_HOST}
      mail__options__port: ${MAIL_PORT:-587}
      mail__options__secure: "false" # STARTTLS on 587
      mail__options__auth__user: ${MAIL_USER}
      mail__options__auth__pass: ${MAIL_PASS}

secure: "false" looks wrong but it isn't. On port 587 the connection starts plain and upgrades with STARTTLS. secure: true is for port 465, where TLS starts straight away. Mixing them up gives you a confusing hang or TLS error, so I left the comment in.

The values lives in /opt/ghost/.env with mode 600.

MAIL_FROM=noreply@example.com
MAIL_HOST=email-smtp.ap-south-1.amazonaws.com
MAIL_PORT=587
MAIL_USER=<access key id>
MAIL_PASS=<derived smtp password>

The sandbox

A new SES account is in the sandbox. You can only send to addresses you have verified yourself, and there's a low daily limit. For my problem that was actually fine at first: the login code goes to me, and I could verify my own address.

aws sesv2 create-email-identity --email-identity you@example.com

SES mails a link to that address, you click it, and now SES will deliver to it. After that I recreated Ghost container, logged out, logged in from a private window and the code arrived. That was a good moment.

But a blog also sends member signup links and staff invites to people I can't verify one by one. So I requested production access from the SES console (Account dashboard, request production access). You describe what you send and how you handle bounces. It got approved and the account moved to 50,000 emails a day, which is way more than this blog will ever need.

Bounces and complaints

I also made sure the account-level suppression list covers both bounces and complaints. With it, SES stops sending to an address that hard bounced or marked you as spam, which protects your sending reputation without any code.

aws sesv2 put-account-suppression-attributes --suppressed-reasons BOUNCE COMPLAINT
aws sesv2 get-account --query 'SuppressionAttributes'

Turning device verification back on

Last step, and the one I really didn't want to forget. I set GHOST_STAFF_DEVICE_VERIFICATION=true again, ran docker compose up -d ghost, and logged in from another browser to be sure the code still comes through. It did.

If you are moving to Ghost 6, send yourself a test mail before you log out of admin for the first time. A staff invite to your own address is enough.