Email delivery combines message structure, SMTP transport and durable work. MimeKit constructs the message, MailKit communicates with the server, and a PostgreSQL outbox preserves delivery intent across restarts. Separating those responsibilities makes failure classification and the side effects of retries easier to reason about.
MimeMessage and multipart bodies
MimeMessage combines headers such as From, To and Subject with a MIME body. BodyBuilder can create text and HTML alternatives through TextBody and HtmlBody. HTML-encode user-controlled text before inserting it into HTML; constructing MIME does not sanitize content.
Parsing one mailbox explicitly avoids interpreting unexpected input as several recipients. Attachments and embedded resources also affect the MIME tree and final size. This example deliberately builds only text and HTML alternatives.
using var message = new MimeMessage();
message.From.Add(new MailboxAddress("Notifications", "sender@example.com"));
message.To.Add(MailboxAddress.Parse("reader@example.com"));
message.Subject = "A short update";
message.Body = new BodyBuilder {
TextBody = "Your request is ready.",
HtmlBody = "<p>Your request is ready.</p>"
}.ToMessageBody();SMTP sessions and STARTTLS
Connecting, negotiating TLS, authenticating, sending and disconnecting are separate steps. SecureSocketOptions.StartTls requires an upgrade, whereas StartTlsWhenAvailable depends on advertised support. They are not equivalent when encryption is mandatory.
A port number alone does not select the correct TLS policy. Configure the mode expected by the provider and preserve certificate validation. Host and credential values below come from external configuration. Cancellation complements a timeout by giving shutdown and operation budgets an explicit owner.
using var smtp = new MailKit.Net.Smtp.SmtpClient { Timeout = 15000 };
await smtp.ConnectAsync(host, port, SecureSocketOptions.StartTls, ct);
await smtp.AuthenticateAsync(userName, password, ct);
await smtp.SendAsync(message, ct);
await smtp.DisconnectAsync(true, ct);4xx, 5xx and network failures
SMTP 4xx generally indicates a temporary failure and 5xx a permanent rejection class. Context still matters: repeated rapid attempts do not repair incorrect credentials, and a timeout can leave acceptance uncertain.
Record the SMTP status and exception category without logging passwords, message bodies or token-bearing links. Temporary failures can receive bounded retries; permanent failures need a visible failed state. Administrative retry should be an explicit operational decision.
MailKit — SmtpCommandException
Transactional outbox and atomic claims
Write the business change and delivery intention in one PostgreSQL transaction. A background worker later selects due Pending rows. Because several workers can read the same candidate, ownership depends on a conditional update and its affected-row result.
Bind the identifier using the database driver. No returned row means the claim was not obtained. A claim timestamp or lease allows recovery from abandoned Sending work. If the original worker may still run when a lease expires, renewal and overlapping execution need an explicit policy.
-- Teaching schema: status is text; $1 is a bound message identifier.
UPDATE email_outbox
SET status = 'Sending', claimed_at = now()
WHERE id = $1 AND status = 'Pending'
RETURNING id;Backoff, jitter and retry semantics
Exponential backoff increases the delay per attempt and caps growth. Jitter avoids synchronizing many failed jobs into another burst. Persist attempt counts, next-attempt time and a short error category so a restart does not reset the delivery policy.
A producer idempotency key can prevent duplicate outbox intentions. It cannot remove the crash window between SMTP acceptance and the Sent update. An outbox therefore does not prove exactly-once delivery through an external mail server. Message-Id is useful for tracing, not a universal deduplication guarantee.
IDataProtector and sensitive payload lifetime
IDataProtector.Protect can protect token-bearing bodies before persistence. Unprotect uses the same purpose. A purpose separates uses but is not a secret key. Losing the key ring can make queued payloads unreadable, which makes key retention part of the backup design.
After success, retaining status, timestamps and attempt counts while clearing the body reduces sensitive-data lifetime. Plain recipient metadata still requires access controls. Oldest-pending age and permanent-failure count provide operational evidence beyond a worker heartbeat.
Microsoft Learn — Data Protection
Related technical articles
- Supabase Storage and S3: signed HTTP requests, streaming and caching
- SignalR and WebSocket: connections, messaging and reconnection
- Phaser and TypeScript: scene lifecycle, time steps and interpolation
- JWT and refresh tokens: validation, rotation and browser sessions
- PostgreSQL and EF Core: DB-first, queries and concurrency