Email, Push and SMS Notifications Done Safely
On this page
Learning Objective
Design a notification service that separates events from delivery, respects user preferences and consent, achieves good email deliverability with SPF, DKIM and DMARC, handles bounces and complaints, and resists template injection, account enumeration and SMS fraud.
Concept Explanation
Notifications look simple until a product has them in earnest: welcome emails, password resets, assignment alerts, weekly digests, browser push, and text messages for verification codes. A maintainable design separates three concerns. Domain code publishes an event, such as TaskAssigned, without knowing how anyone will be told. A notification service decides who should hear about it and through which channels, using the recipient's preferences. Channel adapters, for email, web push, mobile push, and SMS, do the actual delivery through providers, behind an interface, so a provider can be replaced. The flow uses the outbox and queue from Days 66 and 122, so a notification is created reliably with the change that caused it and sent by a worker with retries, and every send carries a deduplication key so a retry cannot deliver the same message twice.
Consent and preferences are legal and product requirements. Distinguish transactional messages, such as a receipt or password reset, which the user needs, from marketing messages, which require consent in many jurisdictions and an easy way to opt out. Store the user's choices per channel and category, honor them in the notification service and not in scattered callers, and include a working unsubscribe link and a one-click unsubscribe header in bulk mail. Do not send more than people want: a digest and a per-user rate limit protect users and your sender reputation.
Email deliverability is an engineering topic. Receiving servers decide whether to trust your mail using three DNS-based mechanisms: SPF lists the servers allowed to send for your domain, DKIM adds a cryptographic signature that proves the message was not altered and came from a key you control, and DMARC tells receivers what to do when checks fail and where to send reports. Google and Yahoo began enforcing requirements for bulk senders in 2024, including authentication, one-click unsubscribe, and a low spam complaint rate. Providers report bounces and complaints through webhooks, which you must consume: keep a suppression list and never send again to an address that hard bounced or complained, since repeated sends damage your reputation for all your mail.
Notifications are also an attack surface. User-supplied text placed in a template, such as a task title, must be encoded for the format, HTML-encoded in HTML mail and stripped of control characters in subjects, or an attacker can inject markup or links into messages that carry your brand. Never build header lines from unvalidated input, since newline characters can add headers or recipients. Account flows must not reveal whether an address is registered: a password reset request returns the same response either way, and the email is sent only if the account exists. Reset and verification tokens should be random, single-use, short-lived, and stored hashed, as in Day 42. Text messages carry a specific fraud: SMS pumping, where attackers trigger verification messages to numbers they profit from, and you pay for each one. Defend with rate limits per number, account, and network, restrict destination countries you do not serve, require a challenge before sending, and monitor cost. Finally, remember that content in a notification leaves your controlled environment, so keep sensitive details out of push and lock-screen text and out of email bodies where a link to the authenticated app will do.
| Concern | Practice | Reason |
|---|---|---|
| Decoupling | Domain event, notification service, channel adapters | Change channels and providers without touching domain code |
| Preferences | Per channel and category, checked centrally | Legal consent and user trust |
| Duplicate sends | Deduplication key per notification and recipient | Retries and at-least-once delivery |
| Deliverability | SPF, DKIM, DMARC, unsubscribe, complaint handling | Mail gets delivered and reputation stays good |
| Templates | Encode user data for the output format | Prevents markup and link injection |
| SMS cost and fraud | Rate limits, country allowlist, challenge before send | Blocks SMS pumping |
Worked Example: A Preference-Aware Sender, Safe Templates, DNS Records and Web Push
The service checks preferences and suppression, renders with encoding, and sends with a dedupe key. The rest shows DNS records and browser push subscription.
public sealed class NotificationService(AppDb db, ITemplateRenderer templates, IEmailSender email, ISmsSender sms, IRateLimiter limiter)
{
public async Task DeliverAsync(NotificationRequest n, CancellationToken ct)
{
// 1. Deduplicate: a retry of the same request must not send twice.
if (!await db.SentNotifications.TryClaimAsync(n.DedupeKey, ct)) return;
var user = await db.Users.AsNoTracking().SingleAsync(u => u.Id == n.UserId, ct);
var prefs = await db.NotificationPrefs.AsNoTracking().SingleAsync(p => p.UserId == n.UserId, ct);
// 2. Respect consent: transactional messages bypass marketing settings, everything else honors them.
if (n.Category != Category.Transactional && !prefs.Allows(n.Category, Channel.Email)) return;
if (await db.EmailSuppressions.AnyAsync(s => s.Address == user.Email, ct)) return; // hard bounce or complaint: never again
// 3. Render with encoding. User-supplied values are data, never markup.
var html = await templates.RenderAsync(n.TemplateName, n.Model, encode: HtmlEncoder.Default, ct);
var subject = SanitizeHeader(n.Subject);
await email.SendAsync(new EmailMessage(user.Email, subject, html, ListUnsubscribe: n.Category != Category.Transactional ? UnsubscribeUrl(user) : null), ct);
}
// Strip line breaks and control characters so input can never add a header or a recipient.
private static string SanitizeHeader(string s) => new string(s.Where(c => !char.IsControl(c)).ToArray())[..Math.Min(s.Length, 200)];
// Verification codes by SMS: limits per number, per account, and per network, plus an allowlist of destination countries.
public async Task<bool> SendVerificationSmsAsync(string e164Number, Guid accountId, string ip, CancellationToken ct)
{
if (!Countries.AllowedPrefixes.Any(e164Number.StartsWith)) return false;
if (!await limiter.AllowAsync($"sms:num:{e164Number}", max: 3, per: TimeSpan.FromHours(1))
|| !await limiter.AllowAsync($"sms:acct:{accountId}", max: 5, per: TimeSpan.FromHours(1))
|| !await limiter.AllowAsync($"sms:ip:{ip}", max: 10, per: TimeSpan.FromHours(1))) return false;
await sms.SendAsync(e164Number, $"Your code is {OtpCode.Generate()}. It expires in 10 minutes.", ct);
return true;
}
}
// A password reset never reveals whether the address exists.
app.MapPost("/api/auth/forgot-password", async (ForgotRequest req, AppDb db, INotificationQueue q, CancellationToken ct) =>
{
var user = await db.Users.SingleOrDefaultAsync(u => u.Email == req.Email.ToLowerInvariant(), ct);
if (user is not null) await q.EnqueueAsync(NotificationRequest.PasswordReset(user, token: ResetTokens.CreateAndStoreHashed(user)), ct);
return Results.Accepted(); // identical response and similar timing either way
});DNS records for the sending domain (values are illustrative):
example.com. TXT "v=spf1 include:_spf.provider.example -all" # who may send
sel1._domainkey.example.com. TXT "v=DKIM1; k=rsa; p=MIIBIjANBgkq..." # public key to verify signatures
_dmarc.example.com. TXT "v=DMARC1; p=quarantine; rua=mailto:dmarc@example.com" # policy and reports; move to reject once clean
Bulk mail headers:
List-Unsubscribe: <https://app.example.com/u/abc123>, <mailto:unsubscribe@example.com>
List-Unsubscribe-Post: List-Unsubscribe=One-Click// Web Push: the service worker receives the push, and the server sends with VAPID keys. Keep the payload free of sensitive content.
const reg = await navigator.serviceWorker.ready;
const sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: vapidPublicKey });
await request('/api/push/subscriptions', z.unknown(), { method: 'POST', body: sub.toJSON() });
// sw.ts
self.addEventListener('push', (e) => {
const data = e.data?.json() ?? {};
e.waitUntil(self.registration.showNotification('New activity', { body: 'Open the app to see details.', data: { url: '/inbox' } })); // no private text on a lock screen
});Notification history in the app, with a read state, is often worth building early. It gives users a place to catch up, it reduces reliance on email for important information, and it is a channel that the user controls entirely.
Real-World Examples
- In February 2024 Google and Yahoo began enforcing new requirements on senders of bulk email: authentication with SPF and DKIM, a DMARC policy, one-click unsubscribe, and a spam complaint rate kept below a threshold, with non-compliant mail at risk of being rejected. The change made email authentication a baseline requirement for any product that sends notifications at volume.
- Telecommunications fraud known as SMS pumping or traffic pumping has led to unexpectedly large bills for companies that send verification codes, because attackers request codes to numbers that share revenue with them. Providers recommend geographic restrictions, per-number and per-network rate limits, and monitoring of conversion rates as defenses.
Review Questions & Answers
Domain code should not know about channels, templates, or user preferences, and centralizing them makes it possible to honor consent consistently, add channels, and replace providers. The domain only publishes what happened.
SPF lists which servers may send mail for the domain, DKIM signs messages so receivers can verify they were not altered and come from a key you control, and DMARC tells receivers how to treat mail that fails those checks and where to report. Together they let receivers trust your mail.
A different response lets an attacker test which addresses have accounts, which enables targeted attacks and privacy leaks. The email is sent only when the account exists, but the visible response and timing stay the same.
Attackers trigger verification messages to numbers they profit from, and the victim pays for each one. Rate limits per number, account, and network, an allowlist of destination countries, a challenge before sending, and cost monitoring reduce it.