In August I moved this blog off Ghost and dropped the newsletter along with it. Moving This Blog From Ghost to Hugo Without Changing a Single Post URL says why. The list had three real subscribers, and RSS-to-email cost $9 to $33 a month at the services I priced. I wrote that automating it was “the wrong instinct at this scale” and that I’d email the three of them myself.

Then someone I interviewed with recently asked me how to subscribe by email. I told them about RSS, and about the fork of Feedcord I maintain that posts RSS to Discord, but they were adamant about email.

So I built it. A push that publishes a post now sends that post to every subscriber, once, from the same workflow that deploys the site. There’s no newsletter platform in the middle. Amazon SES keeps the subscriber list and sends the mail, a GitHub Actions job decides when there’s something to send, and a PowerShell script does the sending.

It took three posts to write up, and this is the first. It covers the sending side: how SES holds the list, how a GitHub Actions job decides a post is new, and how the script avoids mailing anyone twice. The signup form gets the second post, and everything that broke once it was live gets the third.

The blog’s own repo is private (the migration runbook in it names the Azure subscription holding the old Ghost export), so you can’t browse it. A sanitized copy of the code quoted in this series is in my companion repo, under Hugo/new-post-email, with example.com where my domain was.

Stepping outside Microsoft

Nearly everything on this blog is Microsoft’s, and the blog itself runs on Azure Static Web Apps. The Microsoft service for sending mail from an application is Azure Communication Services Email, and normally that’s where I’d have started.

On 23 September 2026 Microsoft announced that Azure Communication Services retires as a standalone offering on 30 September 2028, and Email is on the list of services that go with it. Since 23 October Microsoft has been limiting onboarding to the retiring services, starting with phone numbers, and its retirement and breaking changes guide says more limits can follow at any time. You can still create a new ACS Email resource today. The guide recommends against onboarding new solutions onto it, and I wasn’t going to build a new thing on a service with an end date.

The same guide lists where to go. Microsoft 365 High Volume Email sends to recipients inside your own tenant. Exchange Online is built for person-to-person mail from licensed mailboxes, with rate limits to match. For application mail to outside recipients, which is what a subscriber list is, the guide points at third-party providers on the Microsoft Marketplace. Microsoft’s own answer was to leave Microsoft, and I picked Amazon SES.

SES fit the job. It has contact lists with topics and a hosted unsubscribe page, so I wouldn’t be storing addresses or writing an unsubscribe flow. And it’s pretty cheap for what I was looking for. New accounts start on the Essentials plan, at $0.16 per 1,000 emails with no monthly fee, against the $9 to $33 a month that ruled this out in August. At my current subscriber count that’s well under $0.16 a month, which still keeps the whole blog under a dollar a month.

One email per post

The email is the post’s title, its summary, the title card and a link. There’s no digest and no full text. scripts/Send-PostEmail.ps1 builds it, and you can have it render a post’s email without AWS access and without sending anything:

1
pwsh scripts/Send-PostEmail.ps1 -Slug a-credential-scan-you-have-to-ask-for -PreviewDir ./preview

That writes an .html and a .txt file for each slug you give it. A preview applies the same 14-day age limit as a real send, so add -SkipAgeCheck for an older post. The text part for that post, from my own copy of the script:

1
2
3
4
5
6
7
8
9
A Credential Scan You Have to Ask For

My PowerShell standards asked each project for a credential scan and gave it nothing to run. Now the installer adds one when you name a scanner, and the scan must find a planted key first.

Read it: https://www.techbyjeff.net/a-credential-scan-you-have-to-ask-for/

--
You get this because you asked for an email when Tech by Jeff publishes.
Unsubscribe: {{amazonSESUnsubscribeUrl}}

The HTML part is the same content in a 600-pixel table, with the title card on top and a “Read the post” button. Everything in it comes from the post’s front matter, so a weak summary now reads weakly in every subscriber’s inbox as well as in the post listing. A preview leaves {{amazonSESUnsubscribeUrl}} as it is. SES fills that in when it sends. The companion folder has an example post to try the command on.

A new-post email open in a mail client, with the client's own Unsubscribe button above the title card, the summary and a Read the post button

SES keeps the list

The repo holds no addresses. Subscribers live in an SES contact list named blog, with one topic, new-posts, in us-west-2. The topic’s default is OPT_OUT, so a contact with no recorded preference gets nothing. That default is what makes double opt-in work on the signup side: an address can sit on the list as a pending contact and stay invisible to every send.

If you build this yourself, these are the pieces SES needs before any of the code can run:

  • A domain identity, verified with DKIM, plus a custom MAIL FROM domain. Mine are techbyjeff.net and bounce.techbyjeff.net. The domain already had a p=quarantine DMARC record, and I added a rua address to it so the aggregate reports go somewhere.
  • A configuration set, blog-posts, with bounce and complaint events going through SNS to the news@ mailbox.
  • The contact list and its topic. Mine started with one contact, my own test address.

How you set up DKIM reaches further than deliverability. AWS’s docs say SES’s subscription management, the feature that adds the unsubscribe link later in this post, is available to identities using Easy DKIM. Senders who sign their own mail before handing it to SES don’t get it.

Your SES account starts in the sandbox. AWS’s quota page puts that at 200 messages per 24 hours and one per second, and only to verified addresses. The script paces itself for the one-a-second limit with a 1,100 ms pause after each send, and the pause costs a list this size nothing once the account is out of the sandbox.

My account is out of the sandbox now. AWS says to allow up to 24 hours for production access, and mine came through within minutes.

Signing in to AWS over OIDC

The job that sends has to call AWS, and I didn’t want an access key sitting in the repo’s secrets. You don’t need one. GitHub Actions can hand a job a short-lived OIDC token that says which repo and branch it’s running for, and an IAM role can trust that token directly. On the AWS side that takes GitHub registered as an OIDC identity provider in the account, and a role whose trust policy checks the token’s sub claim. For a branch, GitHub formats that claim as repo:<owner>/<repo>:ref:refs/heads/<branch>.

My role is gh-blog-send. Its trust policy names this repo and refs/heads/main, so a run from any other branch fails at sign-in.

In the workflow it’s a permission and a step, both in workflows/deploy.yml:

1
2
3
4
permissions:
  contents: read
  id-token: write
  actions: read
1
2
3
4
5
6
- name: Sign in to AWS (SES)
  if: steps.newposts.outputs.slugs != ''
  uses: aws-actions/configure-aws-credentials@v6
  with:
    role-to-assume: ${{ vars.AWS_SEND_ROLE_ARN }}
    aws-region: us-west-2

id-token: write is what lets the job ask GitHub for the token. Once you list any permission, every one you didn’t list is dropped, so contents: read is spelled out for the checkout. actions: read is for the step that asks which earlier runs succeeded. Only this job has id-token: write. The build and deploy steps run in a different job and can’t ask AWS for anything.

The role’s permissions policy is narrow, shown here with AWS’s placeholder account ID in place of mine:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
  "Statement": [
    {
      "Effect": "Allow",
      "Condition": {
        "StringEquals": {
          "ses:FromAddress": "news@techbyjeff.net"
        }
      },
      "Action": "ses:SendEmail",
      "Resource": [
        "arn:aws:ses:us-west-2:111122223333:identity/techbyjeff.net",
        "arn:aws:ses:us-west-2:111122223333:configuration-set/blog-posts",
        "arn:aws:ses:us-west-2:111122223333:contact-list/blog"
      ],
      "Sid": "SendAsNews"
    },
    {
      "Effect": "Allow",
      "Action": [
        "ses:ListContacts",
        "ses:GetContact",
        "ses:UpdateContact"
      ],
      "Resource": "arn:aws:ses:us-west-2:111122223333:contact-list/blog",
      "Sid": "ReadAndMarkContacts"
    }
  ],
  "Version": "2012-10-17"
}

It can send only as news@techbyjeff.net, and it can read contacts and update them. It can’t create or delete one. A compromised workflow could mail my existing subscribers, but it couldn’t add a thousand strangers to the list first.

Deciding what counts as a new post

Only a post’s first publish should send. An edit to a live post, a takedown, a draft committed for later: none of those are news. “Published” on this site means the front matter says draft: false, and the workflow already had a helper for that from the IndexNow step. I moved it into a file both steps source, scripts/lib/published.sh:

1
2
3
4
5
published() {
  git show "$1:$2" 2>/dev/null \
    | awk 'NR==1 && /^---/ {f=1; next} f && /^---/ {exit} f' \
    | grep -Eq '^draft:[[:space:]]*false[[:space:]]*$'
}

It reads the post as it was at a given commit, keeps only the front matter, and looks for draft: false. A draft: false inside a code block in the body doesn’t count, because awk stops at the closing ---.

With that helper, you can define a first publish as a post that’s published at the new commit and wasn’t at the old one:

1
2
3
4
5
6
7
8
newly_published() {
  local base="$1" after="$2" f
  git diff --name-only --no-renames "$base" "$after" -- 'content/posts/*.md' | while read -r f; do
    if published "$after" "$f" && ! published "$base" "$f"; then
      basename "$f" .md
    fi
  done
}

--no-renames means a renamed file shows up as a delete and an add. For this comparison that makes a renamed post look brand new, and there’s a guard for it further down.

Measuring from the last green run

My first version compared the push’s own two ends: the commit before the push and the commit after. That has a hole, and I didn’t see it until a later review of the workflow.

Say you push a post with draft: false and the run fails, maybe on a figure with no alt text. Test-Post.ps1 blocks the deploy, so no email goes out, which is correct. You fix the alt text and push again. Now the post is published on both sides of the second push. The comparison finds nothing new, the deploy goes green, and the post is live and mailed to nobody. A queued run that GitHub cancels because a newer push arrived does the same thing.

The fix was to stop trusting the push’s parent and measure from the last commit that made it all the way through:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
pick_base() {
  local after="$1" fallback="$2" sha
  while read -r sha; do
    [ -n "$sha" ] || continue
    [ "$sha" != "$after" ] || continue
    git cat-file -e "${sha}^{commit}" 2>/dev/null || continue
    if git merge-base --is-ancestor "$sha" "$after" 2>/dev/null; then
      printf '%s\n' "$sha"
      return 0
    fi
  done
  if [ -n "$fallback" ] && git cat-file -e "${fallback}^{commit}" 2>/dev/null; then
    printf '%s\n' "$fallback"
  fi
}

It reads the head commits of the workflow’s successful runs, newest first, and prints the first one that’s an ancestor of the commit being deployed. A run whose email job failed isn’t a success, so the next run starts from before it and looks at the same post again. If no successful run turns up, it falls back to the push’s own parent, and with no usable commit at all it prints nothing and no email goes out.

Looking at a post again is safe only because the script refuses to send a post to the same contact twice.

Renames look like new posts

Post URLs here are the filename, so renaming a slug is a delete and an add as far as git diff --no-renames can tell. To the comparison above, a renamed two-year-old post is a first publish. A date check and a bulk check cover that.

The script skips a post dated more than 14 days ago:

1
2
3
4
5
6
7
$age = [datetimeoffset]::UtcNow - $date
if (-not $SkipAgeCheck -and $age.TotalDays -gt $MaxAgeDays) {
    # A renamed slug looks like a brand-new file to the deploy's git diff, and a
    # backdated post is not news. Either way, mailing it would surprise people.
    Write-Note warning "Skipping '$PostSlug': it is dated $($date.ToString('yyyy-MM-dd')), more than $MaxAgeDays days ago. A renamed or backdated post is not a new one."
    return $null
}

And a push that publishes more than two posts at once is treated as a bulk edit, with none of them mailed. That check started out in the PowerShell script as a count of the slugs it was handed. Once the base became the last successful run, the count was wrong, and a review of the pull request caught it with this scenario. Post A publishes and one contact is refused, so the run is red. The push for post B hands the script A and B, the same contact is refused, and the run is red again. Then post C’s push hands it A, B and C. Three is more than two, so the guard calls it a bulk edit, skips all of them and exits 0. The run goes green, the base moves past all three, and C reaches nobody.

The count has to be per push, and only git can tell one push from the next. The guard moved into the shell library:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
newly_published_by_push() {
  local base="$1" after="$2" max="$3" sha prev
  local -A cut=()
  local -a got
  while read -r sha; do
    [ -n "$sha" ] && cut[$sha]=1
  done
  cut[$after]=1
  prev="$base"
  while read -r sha; do
    [ -n "${cut[$sha]:-}" ] || continue
    mapfile -t got < <(newly_published "$prev" "$sha")
    if [ "${#got[@]}" -gt "$max" ]; then
      echo "::warning::The push ending at ${sha:0:7} published ${#got[@]} posts (${got[*]}). More than ${max} in one push is almost certainly a bulk edit, so none of them were emailed. If they really are new, send each one by hand: Actions, 'Send a post by email', mode live." >&2
    elif [ "${#got[@]}" -gt 0 ]; then
      # Keep only what newly_published <base> <after> would print: a post published here
      # may have gone back to draft in a later push, or have been live at the base and
      # taken down and put back in between.
      for f in "${got[@]}"; do
        if published "$after" "content/posts/${f}.md" && ! published "$base" "content/posts/${f}.md"; then
          printf '%s\n' "$f"
        fi
      done
    fi
    prev="$sha"
  done < <(git rev-list --topo-order --reverse --ancestry-path "${base}..${after}") \
    | awk '!seen[$0]++'
}

It walks the commits from the base to the new head and cuts the range at every commit that was the head of a workflow run. Each segment is one push, and each segment gets its own count. A segment over the limit is left out, and if you did mean to publish that many at once, the warning tells you how to send them by hand.

If a push’s SHA is missing from the list of cut points, two pushes get counted as one. The guard gets stricter in that case and errs toward skipping.

A job of its own

The first version was three steps at the end of the deploy job, with continue-on-error on the send to keep a mail problem from failing a deploy. That kept the deploy safe and hid every failure behind a green check, where you’d have to open the log to find it. It’s now a second job:

1
2
3
4
5
email:
  name: Email subscribers
  needs: build_and_deploy
  if: github.ref == 'refs/heads/main' && contains(fromJSON('["self","live"]'), vars.NEWSLETTER_MODE)
  runs-on: ubuntu-latest
A deploy.yml run on GitHub Actions with a build_and_deploy job that took 2m 28s feeding a separate Email subscribers job that took 14s

needs: build_and_deploy means the site is already live when this starts. The if is the off switch, and NEWSLETTER_MODE gets its own section below. The job’s first real step finds the posts:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# pick_base and newly_published, with the reasoning, are in this file.
source scripts/lib/published.sh
if ! runs=$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/deploy.yml/runs?branch=main&status=success&per_page=50" \
      --jq '.workflow_runs[].head_sha'); then
  echo "::warning::Could not list earlier runs; comparing against this push's own parent instead."
  runs=""
fi
base=$(printf '%s\n' "$runs" | pick_base "$AFTER" "$BEFORE")
if [ -z "$base" ]; then
  echo "No usable base commit (no earlier successful run, new branch or force push); not emailing."
  exit 0
fi
echo "Comparing ${base} to ${AFTER}"
# Every run's head, whatever its outcome, marks where one push ended, so the
# bulk guard can count each push's posts on its own. Without them it would
# count everything since the base as one push and could skip a real post for
# good, so fail instead: the run goes red and the next one looks again.
if ! cuts=$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/deploy.yml/runs?branch=main&per_page=100" \
      --jq '.workflow_runs[].head_sha'); then
  echo "::error::Could not list this workflow's runs to tell pushes apart; not emailing. The next run will look at these posts again."
  exit 1
fi
slugs=$(printf '%s\n%s\n' "$cuts" "$BEFORE" | newly_published_by_push "$base" "$AFTER" 2 | xargs)
echo "Newly published: ${slugs:-none}"
echo "slugs=${slugs}" >> "$GITHUB_OUTPUT"

That step asks the Actions API for the workflow’s successful runs, which pick_base reads, and then for every run whatever its outcome, because each run’s head commit marks where one push ended. The calls fail differently. If the list of successful runs can’t be fetched, the step warns and falls back to the push’s own parent. If the list of all runs can’t be fetched, the step exits 1, because guessing at push boundaries could skip a real post for good.

There’s no continue-on-error on the send anymore. If something that was meant to go out didn’t, the script exits 1 and the run turns red, with the deploy job above it still green. That red run is also what tells the next run to look at the post again. A post skipped for its age or for email: false is a warning and exits 0.

The job has its own concurrency group:

1
2
3
concurrency:
  group: newsletter
  cancel-in-progress: false

The manual test workflow uses the same group, so two sends can’t run at once and race each other’s per-contact records. The deploy job has a separate group, deploy, so a long send doesn’t hold up the next deploy.

There’s a catch in how groups queue. By default a group holds one running job and one pending, and a third that arrives cancels the pending one. A canceled email job leaves its run not a success, so the next run of the workflow picks its posts up. In May 2026 GitHub added queue: max for concurrency groups, which lets more than one run wait in line. The workflow doesn’t set it yet.

One recipient per send

If you’re on the list, you get your own copy. The script reads the opted-in contacts for the topic and sends each of them a separate message:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
function Send-PostMail([string] $To, $Post) {
    # -NoRetry: the CLI must not send this twice on its own. See Invoke-Ses.
    $result = Invoke-Ses 'send-email' -NoRetry -Request @{
        FromEmailAddress      = $From
        Destination           = @{ ToAddresses = @($To) }
        ConfigurationSetName  = $ConfigurationSet
        # This is what makes SES add List-Unsubscribe and List-Unsubscribe-Post and fill
        # {{amazonSESUnsubscribeUrl}}. It only does so for a single-recipient send.
        ListManagementOptions = @{ ContactListName = $List; TopicName = $Topic }
        Content               = @{ Simple = @{
                Subject = @{ Data = $Post.Title; Charset = 'UTF-8' }
                Body    = @{
                    Text = @{ Data = (Format-PostText $Post); Charset = 'UTF-8' }
                    Html = @{ Data = (Format-PostHtml $Post); Charset = 'UTF-8' }
                }
            }
        }
    }
    return $result.MessageId
}

ListManagementOptions is the reason I’m not writing an unsubscribe system. With it set, you get one from SES: it adds the List-Unsubscribe and List-Unsubscribe-Post headers, fills {{amazonSESUnsubscribeUrl}} in the body, hosts the unsubscribe page, and records the opt-out on the contact. If your mail client supports one-click unsubscribe, it shows its own button at the top of the message. AWS’s docs say the headers and the link are added only when the email goes to a single recipient, so there’s no BCC shortcut here even for a small list.

Every SES call goes through the AWS CLI with --cli-input-json. That keeps the script free of modules, the same as Test-Post.ps1, so it runs on a stock runner.

Sending, sent, failed

A deploy can be re-run. A job can die halfway down the list. I wanted a re-run to carry on where the last one stopped, and I wanted the bad case to be a missed email and not a second copy of one.

The state lives on each contact, in the free-form attributes SES lets you store there:

1
{"posts":{"some-post":"sent","another-post":"sending"}}

Before a send, the script records the post as sending. After SES accepts the message, sent. For each recipient the loop reads the contact first:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# Read fresh for every post, so the second post of a push sees the first's
# state. One contact that cannot be read must not stop the rest of the list.
try { $attrs = Get-ContactAttribute $to }
catch {
    $unread++; $failed++
    Write-Note error "Could not read a recipient's record for '$s', so it was not sent to them; a later run will retry: $(& $short $_.Exception.Message)"
    continue
}

$state = Get-PostState $attrs $s
if ($state -eq 'sent') { $skipped++; continue }
if ($state -eq 'sending') {
    # An earlier run recorded 'sending' and never learned the outcome. SES may
    # have taken it, so leave it: a duplicate is worse than a gap.
    $stuck++; Write-Note warning "A recipient of '$s' was left at 'sending' by an earlier run and was not retried."
    continue
}
# No state, or 'failed' (SES refused it before): safe to send.

A contact that can’t be read is counted and skipped, and the rest of the list still gets the post. sending means an earlier run started a send and didn’t learn how it ended. SES may have taken the message, so the script leaves it alone and reports it.

When a send throws, the question is whether SES refused the message or whether I just don’t know:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
try { $id = Send-PostMail $to $post }
catch {
    $msg = $_.Exception.Message
    if (Test-SesRejected $msg) {
        $refused++; $failed++
        Write-Note error "SES refused a send of '$s'; a later run will retry it: $(& $short $msg)"
        try { Set-PostState $to $attrs $s 'failed' $msg }
        catch { Write-Note warning "Could not record that refusal, so that recipient stays at 'sending' and will not be retried: $(& $short $_.Exception.Message)" }
    }
    else {
        $unknown++; $failed++
        Write-Note warning "A send of '$s' got no clear answer from SES, so it may have been delivered. Left at 'sending' and not retried: $(& $short $msg)"
    }
    Start-Sleep -Milliseconds $PaceMs
    continue
}

Only a definite refusal is recorded as failed, the one state a later run retries:

1
2
3
4
function Test-SesRejected([string] $Message) {
    if ($Message -notmatch 'An error occurred \((?<code>[A-Za-z]+)\)') { return $false }
    return $Matches['code'] -notmatch '^(Internal|ServiceUnavailable)'
}

If you see An error occurred (AccessDeniedException), SES answered and said no, so the message wasn’t delivered. A timeout or a dropped connection has no such line. Neither does a send that worked followed by a failure to write sent. Server-side errors are treated as unknown too, since SES could have accepted the message before failing. All of those stay at sending.

If you’re a subscriber, your address stays out of the build log. The log gets a count and the error text, with the address cut out of it. Each post ends with one line in the job’s Summary tab:

1
Add-Summary "- $(if ($dry) { 'would send' } else { 'sent' }): $sent, already sent: $skipped, refused: $refused, not attempted: $unread, left at sending: $stuck, outcome unknown: $unknown, recipients: $($recipients.Count)"

Duplicates caught before the merge

The first commit of the script didn’t work this way, and it could send a post twice by more than one route. A review before the merge found them. I confirmed each one by running the script twice in a row against a stand-in for the AWS CLI that counts deliveries, the way a deploy re-run would.

In that first commit each contact kept a single lastPost value. After a push that published two posts, the second overwrote the first on every contact. On a re-run neither one looked finished, and both posts went out again. That’s why the state is now a map.

The send and the bookkeeping also shared one try:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Set-SendMarker $to $attrs $s 'sending' $null
try {
    $id = Send-PostMail $to $post
    Set-SendMarker $to $attrs $s 'sent' $null
    $sent++
    Write-Host "  sent ($id)"
}
catch {
    $failed++
    $msg = $_.Exception.Message
    # Never log the address: the error goes on the contact, the log gets a count.
    Write-Note error "A send of '$s' failed: $($msg.Substring(0, [Math]::Min(200, $msg.Length)))"
    try { Set-SendMarker $to $attrs $s 'failed' $msg } catch { Write-Note warning "Could not mark the failed send: $($_.Exception.Message)" }
}

If SES took the message and the write of sent then failed, the catch recorded failed, and failed is the state the next run retries. A timeout after SES had accepted the message landed in the same catch. In the current loop the send and each state write are separate statements with their own handling.

Scenario, run twiceDelivered beforeDelivered after
Two-post push42
Send works, the sent write fails21
SES delivers, the CLI times out21
SES rejects the message0, then retried0, then retried

One more route turned up later. The AWS CLI retries a timed-out call by itself, and a retried send-email can deliver a message SES had already taken. For this one command, Invoke-Ses in scripts/lib/Ses.ps1 turns that off:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$priorAttempts = $env:AWS_MAX_ATTEMPTS
if ($NoRetry) { $env:AWS_MAX_ATTEMPTS = '1' }
try {
    $out = & aws sesv2 $Command --cli-input-json $json --region $Region --output json 2>&1
    $code = $LASTEXITCODE
}
finally {
    if ($NoRetry) {
        if ($null -eq $priorAttempts) { Remove-Item Env:AWS_MAX_ATTEMPTS -ErrorAction SilentlyContinue }
        else { $env:AWS_MAX_ATTEMPTS = $priorAttempts }
    }
}

AWS_MAX_ATTEMPTS=1 applies only to the send. Reads and contact updates keep the CLI’s normal retries, because repeating those does no harm.

The off switch and the test send

A repo variable, NEWSLETTER_MODE, decides how far any of this goes:

NEWSLETTER_MODEEffect
unset or offThe email job is skipped and nothing signs in to AWS
selfSends only to the address in the NEWSLETTER_TEST_ADDRESS secret
liveSends to every opted-in contact

You change it in the repo’s settings with no commit, so it doubles as the rollback. Merging the first PR sent nothing because the variable didn’t exist yet.

A second workflow, workflows/newsletter-test.yml, shows up in the Actions tab as “Send a post by email”. You run it by hand, and it sends one live post through the same role, list and script. In self mode it goes to the test address and skips the 14-day limit, since the point is to re-send something already published. In live mode it goes to everyone, for a post the deploy skipped. It keeps the 14-day limit there, and it refuses unless NEWSLETTER_MODE is live too, so the off switch still switches everything off.

The Run workflow form for Send a post by email, with a required slug field and a mode dropdown set to self, beside four earlier runs

You can also run the script with -WhatIf. Against the real list that does every read, sends nothing and writes no state, which is how I checked the recipient query before the first real send.

Before sending, the script waits for the post to answer 200:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
function Wait-PostLive($Post) {
    # SWA has usually finished by the time this step runs, but a reader clicking into a
    # 404 is the worst first impression, so check rather than assume.
    $deadline = [datetime]::UtcNow.AddSeconds($WaitSeconds)
    do {
        try {
            $r = Invoke-WebRequest -Uri $Post.Url -Method Head -SkipHttpErrorCheck -MaximumRedirection 3 -TimeoutSec 20
            if ($r.StatusCode -eq 200) { return $true }
            Write-Host "  $($Post.Url) answered $($r.StatusCode); waiting."
        }
        catch { Write-Host "  $($Post.Url) not reachable yet: $($_.Exception.Message)" }
        Start-Sleep -Seconds 15
    } while ([datetime]::UtcNow -lt $deadline)
    return $false
}

Azure Static Web Apps has usually finished by the time the email job starts. The script checks anyway, every 15 seconds for up to five minutes. If the post still isn’t up, the script doesn’t send it, the run goes red, and a later run tries again.

An apostrophe in the subject line

The front matter reader used to live inside Test-Post.ps1, and it had a bug that validation had no reason to notice. YAML escapes an apostrophe inside a single-quoted string by doubling it. Three of my post titles do that, and the reader handed them back with both quotes intact. For a validator checking that title exists, that’s fine. For an email, the subject line would have read Couldn''t.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function Remove-YamlQuote {
    param([string] $Value)
    $v = $Value.Trim()
    if ($v.Length -ge 2) {
        # A single-quoted YAML scalar escapes an apostrophe by doubling it, so
        # 'Couldn''t' means Couldn't. A validator never needs the real text, but an
        # email subject line shows the doubled quote to every reader.
        if ($v[0] -eq "'" -and $v[-1] -eq "'") {
            return $v.Substring(1, $v.Length - 2).Replace("''", "'")
        }
        if ($v[0] -eq '"' -and $v[-1] -eq '"') {
            return $v.Substring(1, $v.Length - 2)
        }
    }
    return $v
}

The reader moved to scripts/lib/FrontMatter.ps1 so both scripts share one copy, and Test-Post.ps1 picked up a rule on the way. A post can opt out of the email with email: false in its front matter. The script compares that value to the string false, so email: no would have looked like an opt-out to you and sent the post anyway. Anything other than true or false is now a validation error.

With all that said, the first email my subscribers get will be this post about building the thing that sends it, which I find amusing.

In August the automation cost more than the work it replaced. The sending side is now one script, a shell library and one extra job in a workflow that was already there, and a post that leaves draft goes to every subscriber on the next push.