# LeadPilot — Email Architecture & Compliance

**Document Version:** 1.0.0 (Phase 9B)

---

## 1. Provider Architecture

```
MailService (Singleton)
      │
      └── MailProviderContract
                │
                ├── LaravelMailProvider (default: env MAIL_MAILER)
                └── MockMailProvider    (app()->environment('testing'))
```

---

## 2. Email Header Injection Prevention

All email header fields are sanitized before dispatch:

```php
// Strip CR/LF from all user-influenced fields
$cleanEmail   = trim(preg_replace('/[\r\n]/', '', $lead->email));
$cleanName    = trim(preg_replace('/[\r\n]/', '', $lead->full_name));
$cleanSubject = trim(preg_replace('/[\r\n]/', '', $subject));
```

---

## 3. Sender Identity

Production emails are sent from:
- **From Address**: `config('mail.from.address')` (set in `.env` as `MAIL_FROM_ADDRESS`)
- **From Name**: Workspace name (scoped to the tenant)
- **Reply-To**: Optional per-workspace override

---

## 4. Template Variable Allowlist

Only the following variables are substituted. All unknown variables are left as-is and do NOT execute code:

| Variable              | Source              |
|-----------------------|---------------------|
| `{{lead.name}}`       | `Lead::full_name`   |
| `{{lead.first_name}}` | `Lead::first_name`  |
| `{{lead.last_name}}`  | `Lead::last_name`   |
| `{{lead.company}}`    | `Lead::company`     |
| `{{lead.service}}`    | `Lead::service_interest` |
| `{{lead.email}}`      | `Lead::email`       |
| `{{workspace.name}}`  | `Workspace::name`   |

---

## 5. Script Stripping

Before variable substitution, the following are stripped:

```php
preg_replace('/\<\?php.*?\?\>/is', '', $content);
preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $clean);
```

---

## 6. Compliance Notes

- LeadPilot is designed for **legitimate enquiry follow-up only** — not unsolicited campaigns.
- Opt-out: If a `Lead::email_opted_out = true` flag is set, the `MailService` should check this before dispatch (configurable in future).
- All emails respect the workspace's configured sender identity.
