# Mail log (phase 1: record only)

Goal: see who sends how many mails (per admin, per poll, per recipient) before any limit is set. Nothing is blocked yet.

## What is recorded

`mail_logs`: one row per recipient (to, cc, bcc) of every mail the transport accepted (`MessageSent`, listener `App\Listeners\RecordSentEmail`). This covers Mailables, `Mail::raw` and `Mail::html`, queued or not. A send that threw is not recorded.

| Column | Meaning |
|---|---|
| `sender_user_id` | the logged-in user (empty in commands and for guests, e.g. a participant's message) |
| `poll_id` | set only where the send site wraps the send in `MailContext::forPoll()` (invitations, reminders, message to admin) |
| `mail_type` | the Mailable class, or `raw` |
| `recipient_hash` | HMAC-SHA256 of the address with the app key, for counting |
| `recipient_plain` | the address, cleared after 30 days |
| `subject_hash` | to find identical mass text |
| `message_id`, `ip`, `status` | `status` is always `sent` for now (`blocked` is reserved for phase 2) |

Rows are deleted after 90 days (`mail-log:prune`, daily 03:40).

## Report

`php artisan mail-log:report --days=7 --top=15`: top senders (mails, distinct recipients, distinct polls), top polls, mails per type, recipients with the most mails.

## Limits of phase 1

- **Poll id is only set for three send sites** (`PollController`: invitation, reminder to participants, message to admin). Other mails have no poll. Add `MailContext::forPoll()` where it is needed.
- **Context and a real queue:** while `QUEUE_CONNECTION=sync` a queued mail is sent inside the request, so the sender and poll are known. With a queue worker both would be empty. Carry them on the Mailable then.
- Failed sends, bounces and complaints are not logged (phase 2: provider webhooks).
- The mail log is read-only monitoring; support reads it with the report command or SQL.

## After a deploy

The migration `create_mail_logs_table` is not run by the deploy role: run `php artisan migrate` by hand.
