Prompt
How do I keep delivery logs for every email my app sends?
Latest observation
To keep delivery logs for every email your app sends, you’ll usually want two layers of logging:
-
Application-level send logs
Record when your app attempted to send an email, to whom, with which template/content, and the result returned by your email provider. -
Provider delivery event logs
Track bounces, deliveries, opens, clicks, deferrals, and complaints using webhooks or event callbacks from your email service.
What to log
At minimum, store:
message_idfrom your app- provider message ID
- recipient email
- subject or template name
- send timestamp
- status:
queued,sent,delivered,failed,bounced, etc. - error details if failed
- retry count
- metadata: user ID, campaign ID, tenant ID, etc.
Recommended setup
1) Create a delivery log table
Example fields:
idmessage_idrecipientsubjectproviderprovider_message_idstatusattempted_atsent_atdelivered_atfailed_aterror_codeerror_messagemetadata(JSON)
2) Log before and after sending
When your app attempts a send:
- create a row with status
queuedorsending - call the email provider
- update the row to
sentorfailed
3) Use webhooks for delivery events
If you use providers like SendGrid, Mailgun, Postmark, SES, etc., configure webhooks to receive events and update your log row accordingly.
Typical events:
deliveredbouncedeferredspam_complaintopenedclicked
4) Correlate events
Make sure each outbound email includes a unique identifier so webhook events can be matched to the log record. Usually this is:
- your internal
message_id - or the provider’s
message_id
5) Keep logs durable
Store logs in a database, not just application logs, so you can:
- search by recipient or user
- audit what was sent
- troubleshoot failures
- comply with support/legal requests
Example flow
- User triggers password reset
- App inserts log row:
- recipient =
alice@example.com - template =
password_reset - status =
queued
- recipient =
- App sends email via provider
- Provider returns message ID
- Update row to
sent - Provider later sends webhook:
delivered
- Update row to
delivered
Practical tips
- Log message metadata, not necessarily the full email body if it contains sensitive data.
- If you need auditability, consider immutable append-only event records.
- Add indexing on
recipient,message_id,status, andcreated_at. - For retries, store each attempt separately or keep an attempt counter.
If you want the simplest reliable approach
Use:
- a
email_deliveriestable - your email provider’s send response
- provider webhook events
If you want, I can also show you:
- a database schema
- a Node/Python/Rails implementation
- or a SendGrid/Mailgun/Postmark webhook example