# LeadMail Integration

Chatwoot is configured to use LeadMail API for sending transactional emails (password resets, invites, notifications, etc.).

## Configuration

Set these environment variables:

```env
LEADMAIL_API_TOKEN=lm_your_token_here
LEADMAIL_API_URL=https://mail.leadmagnet.dev/api/v1
```

## How It Works

1. **Priority**: If `LEADMAIL_API_TOKEN` is present, LeadMail is used. Otherwise, falls back to SMTP.
2. **Async Processing**: LeadMail accepts emails asynchronously (202 Accepted) and queues them for background processing.
3. **Email Verification**: Includes Verifalia verification to filter invalid/disposable emails (configurable via `on_verification_failure` option).
4. **Message Tracking**: Each sent email receives a `log_id` stored in the `X-LeadMail-Log-ID` header for debugging.

## Email Types Using This

All transactional emails:
- User account invitations
- Password reset links
- Account notifications (e.g., OAuth disconnects)
- Digest emails
- System-generated messages

## Not Affected

- **Email inbox replies**: Each email inbox can use its own SMTP credentials (configured per-inbox in dashboard)
- **Conversation messages**: Only transactional system emails use LeadMail

## Fallback Behavior

If LeadMail API is unavailable:
- Errors are logged with the failed payload
- Delivery exceptions propagate (configured via `config.action_mailer.raise_delivery_errors`)
- SMTP fallback is NOT automatic; you must not set `LEADMAIL_API_TOKEN` to use SMTP

## Debugging

Check logs for:
```
Email sent via LeadMail: log_id=12345, to=["recipient@example.com"]
```

Failures include the payload for investigation:
```
LeadMail delivery failed: [error message]
Payload: {...}
```

## Testing

The delivery method is fully spec'd in `spec/delivery_methods/leadmail_delivery_spec.rb`.

Run tests:
```bash
bundle exec rspec spec/delivery_methods/leadmail_delivery_spec.rb
```
