Day 5 · HTML email, images, code & security

Sending email from code: SMTP vs API, queues, retries and webhooks

lesson 16 / 1912 min1 labpublished
Course contents
On this page
  1. SMTP, an API, or a local relay
  2. Never send inside the web request
  3. After “250”: bounces, complaints and deliveries
  4. Headers your application should set
  5. Security
  6. Testing without emailing real people

Password resets, receipts, invitations, alerts: for many organizations, more email is sent by software than by people, and it’s the email users notice most when it doesn’t arrive. Sending one message from code takes five lines. Sending reliably, at volume, with correct authentication, without duplicates, without becoming a spam relay, and without emailing real customers from a test environment, takes the design in this lesson.

SMTP, an API, or a local relay

OptionHow it worksProsCons
SMTP to your provider or ESPThe app connects to smtp.example-esp.com:587 with credentialsStandard; every language has a library; easy to switch providersA slow protocol for high volume; errors are only “accepted” or a code
ESP HTTP APIPOST a JSON message to the ESPFast, batchable, templates and metadata, richer errorsTies your code to one vendor’s API
Local relayThe app hands mail to Postfix on localhost, which queues and forwards it to the ESP (relayhost)Instant for the app; the queue survives ESP outagesOne more server to run and monitor

Never send directly from application servers to recipients’ MX hosts on port 25: you’d need your own IP reputation, PTR, DKIM and queueing, port 25 is blocked on most clouds, and you’d be building a worse ESP. Use an ESP (Amazon SES, SendGrid, Mailgun, Postmark, Brevo and many others) or your provider’s relay, and keep the application’s job small: build a correct message and hand it over.

Never send inside the web request

Sending takes from tens of milliseconds to many seconds, and the relay can be down. If the HTTP request that handles “forgot password” waits for SMTP, a slow relay makes your site slow, and a failure loses the email or shows the user an error. Instead:

  1. The request handler writes a job to a queue (a database table, Redis, SQS, RabbitMQ, your framework’s job system) with everything needed to build the message, and returns at once.
  2. A worker takes jobs, builds and sends the message, and records the result.
  3. Failures are retried according to their kind.

Retries done right

ResultMeaningWhat the worker does
Connection error, timeout, 4xxTemporaryRetry with exponential backoff and jitter (1 min, 2, 4, 8… up to hours), then give up and alert
5xx for a recipient (550 5.1.1)Permanent for that addressDon’t retry; mark the address undeliverable
5xx for authentication or policy (535, 550 5.7.x from your relay)Your configuration is brokenStop the queue and alert a human; retrying won’t help
Success (250)The relay accepted itRecord the Message-ID; delivery events come later

Make sending idempotent: give each job a unique key (for example “reset email for request 8f2c”) and record that it was sent, so a worker that crashes after sending but before acknowledging the job doesn’t send a second copy when the job is retried.

After “250”: bounces, complaints and deliveries

The 250 from your relay or ESP only means they accepted the message. What happens next arrives later, asynchronously:

  • Bounces: the recipient’s server refused the message after your ESP accepted it.
  • Complaints: the recipient clicked “Report spam” (from feedback loops).
  • Deliveries, opens, clicks: if you track them.

ESPs report these through webhooks (an HTTPS endpoint you provide, which they call with a JSON event) or notifications (Amazon SES publishes to SNS). If you run your own relay, give each message a unique bounce address (VERP, variable envelope return path: bounces+<message-token>@mail.example.com), so an incoming bounce tells you exactly which message and recipient failed.

Whatever the source, the result goes into a suppression list that every send checks first: hard bounces and complaints are never mailed again (until the user updates their address or re-subscribes). Sending repeatedly to addresses that bounce or complained is the quickest way to ruin your sending reputation, and your ESP will suspend your account for it.

Headers your application should set

HeaderWhy
From with your domain (or a sending subdomain), aligned with DKIMDMARC (lesson 10); never use a user’s address as From
Reply-ToWhere replies should go, if not to From (support, the user who triggered it)
Message-ID with your domainUnique ID for logs and threading; many libraries add one, but make sure the domain is yours
DateRequired
Auto-Submitted: auto-generatedStops out-of-office replies and other robots from answering (RFC 3834; see auto-responders)
List-Unsubscribe and List-Unsubscribe-PostRequired for bulk and subscribed mail (lesson 13)
A correlation header (X-Entity-Ref-ID, X-Job-ID…)Ties a message to your records when it comes back in a bounce

Gmail groups messages into conversations by subject and references; if every notification of a kind has the same subject (“New login”), give each a unique Message-ID and no References, or include something unique in the subject, so they don’t collapse into one thread.

Security

  • Contact forms are open relays waiting to happen. Never put the visitor’s address in From (it fails DMARC, and attackers will use your form to send spam “from” any address). Send from your own address, to your own inbox, with the visitor’s address in Reply-To. Rate-limit the form and add a CAPTCHA.
  • Header injection. Never build headers by concatenating strings with user input: a name containing \r\nBcc: victims... adds recipients. Use a real email library, which encodes or rejects line breaks.
  • HTML injection. Escape user data in HTML templates exactly as on a web page. An attacker who can put their own link in your password-reset email can phish your users with your own reputation.
  • Credentials. Store SMTP passwords and API keys in a secret manager, use keys scoped to “send only” and to specific domains, rotate them, and alert on unusual volume: leaked ESP keys are sold and used for spam within hours.
  • Don’t let users choose arbitrary sender domains in multi-tenant products without verifying they own them.

Testing without emailing real people

  • In development, send to a local mail catcher such as Mailpit: it accepts everything on port 1025, delivers nothing, and shows the messages (HTML, text, headers, attachments) in a web interface. docker run -p 8025:8025 -p 1025:1025 axllent/mailpit.
  • In staging, make it impossible to email customers: route all mail to a catcher, or allow only recipients on an allow-list in your test domain. “We emailed 40,000 customers from the test environment” is a real, recurring incident.
  • In automated tests, assert on the message object your code builds (headers, recipients, links, no unrendered template variables) rather than sending.
  • Before a template goes live, send it to real test accounts at Gmail, Outlook.com and Apple, and check rendering, authentication (Authentication-Results) and placement.