# Email Templates Guide

This document provides comprehensive documentation for the Lilith Notification
Service email system, including template management, provider configuration, and
unsubscribe handling.

## Overview

The Email System provides:

- **Email Providers**: SendGrid and AWS SES integration
- **Template System**: Variable-based templates with localization
- **Unsubscribe Handling**: CAN-SPAM and GDPR compliant one-click unsubscribe
- **Tracking**: Open and click tracking support
- **Attachments**: Full MIME support for attachments

---

## Table of Contents

1. [Email Providers](#email-providers)
2. [Template System](#template-system)
3. [Sending Emails](#sending-emails)
4. [Unsubscribe Handling](#unsubscribe-handling)
5. [Bounce & Complaint Handling](#bounce--complaint-handling)
6. [Email Tracking](#email-tracking)
7. [Error Handling](#error-handling)
8. [SDK Integration](#sdk-integration)

---

## Email Providers

### SendGrid

#### Environment Variables

| Variable              | Required | Description                    |
| --------------------- | -------- | ------------------------------ |
| `SENDGRID_API_KEY`    | Yes      | SendGrid API key               |
| `SENDGRID_FROM_EMAIL` | No       | Default sender email           |
| `SENDGRID_SANDBOX`    | No       | Enable sandbox mode (`'true'`) |

#### Configuration

```typescript
interface SendGridConfig {
  apiKey: string;
  defaultFrom?: string;
  sandbox?: boolean;
}
```

#### Creating Provider

```typescript
import {
  SendGridEmailProvider,
  createSendGridProviderFromEnv,
} from '@lilith/notification/dispatch';

// From environment
const sendgrid = createSendGridProviderFromEnv();

// Manual configuration
const sendgrid = new SendGridEmailProvider({
  apiKey: 'SG.xxx...',
  defaultFrom: 'noreply@lilith.app',
  sandbox: false,
});
```

### AWS SES

#### Environment Variables

| Variable                | Required | Description                    |
| ----------------------- | -------- | ------------------------------ |
| `AWS_REGION`            | Yes      | AWS region (e.g., `us-east-1`) |
| `AWS_ACCESS_KEY_ID`     | No\*     | AWS access key                 |
| `AWS_SECRET_ACCESS_KEY` | No\*     | AWS secret key                 |
| `SES_FROM_EMAIL`        | No       | Default sender email           |
| `SES_CONFIGURATION_SET` | No       | Configuration set for tracking |
| `SES_SANDBOX`           | No       | Enable sandbox mode            |

\*IAM roles are used if credentials are not provided.

#### Configuration

```typescript
interface SESConfig {
  region: string;
  accessKeyId?: string;
  secretAccessKey?: string;
  defaultFrom?: string;
  configurationSet?: string;
  sandbox?: boolean;
}
```

#### Creating Provider

```typescript
import {
  SESEmailProvider,
  createSESProviderFromEnv,
} from '@lilith/notification/dispatch';

// From environment
const ses = createSESProviderFromEnv();

// Manual configuration
const ses = new SESEmailProvider({
  region: 'us-east-1',
  defaultFrom: 'noreply@lilith.app',
  configurationSet: 'lilith-tracking',
});
```

### Provider Selection

```typescript
import { createDispatcher } from '@lilith/notification/dispatch';

// Auto-select from environment
const dispatcher = createDispatcher();

// Explicit provider selection
const dispatcher = createDispatcher({
  config: {
    email: {
      provider: 'sendgrid', // 'sendgrid' | 'ses' | 'mock'
      apiKey: 'SG.xxx...',
      defaultFrom: 'noreply@lilith.app',
    },
  },
});
```

---

## Template System

### Template Structure

```typescript
interface NotificationTemplate {
  id: string;
  name: string;
  type: 'push' | 'email' | 'sms';
  subject?: string; // For email templates
  body: string; // Template content with {{variables}}
  variables: string[]; // List of variable names
  locales: Record<string, LocalizedTemplate>;
  created_at: string;
  version: number;
}

interface LocalizedTemplate {
  subject?: string;
  body: string;
}
```

### Creating Templates

```typescript
// POST /v1/notification-templates
const template = await client.post('/v1/notification-templates', {
  name: 'welcome_email',
  type: 'email',
  subject: 'Welcome to Lilith, {{user_name}}!',
  body: `
    <h1>Welcome, {{user_name}}!</h1>
    <p>Thank you for joining Lilith. Your meditation journey begins now.</p>
    <p>Start your first session: <a href="{{app_url}}">Open App</a></p>
  `,
  variables: ['user_name', 'app_url'],
  locales: {
    es: {
      subject: 'Bienvenido a Lilith, {{user_name}}!',
      body: '<h1>Bienvenido, {{user_name}}!</h1>...',
    },
    ja: {
      subject: 'Lilithへようこそ、{{user_name}}さん！',
      body: '<h1>ようこそ、{{user_name}}さん！</h1>...',
    },
  },
});
```

### Template Variables

Use `{{variable_name}}` syntax for dynamic content:

```typescript
import { renderTemplate } from '@lilith/notification/helpers';

const template = 'Hello, {{user_name}}! Your code is {{code}}.';
const variables = { user_name: 'Sarah', code: '123456' };

const rendered = renderTemplate(template, variables);
// Output: "Hello, Sarah! Your code is 123456."
```

### Standard Email Templates

#### Welcome Email

```typescript
{
  name: 'welcome_email',
  type: 'email',
  subject: 'Welcome to Lilith!',
  body: `
    <h1>Welcome!</h1>
    <p>Hi {{user_name}},</p>
    <p>Your account has been created.</p>
    <a href="{{verify_url}}">Verify Email</a>
  `,
  variables: ['user_name', 'verify_url']
}
```

#### Password Reset

```typescript
{
  name: 'password_reset',
  type: 'email',
  subject: 'Reset Your Password',
  body: `
    <h1>Password Reset</h1>
    <p>Click below to reset your password:</p>
    <a href="{{reset_url}}">Reset Password</a>
    <p>This link expires in {{expires_minutes}} minutes.</p>
  `,
  variables: ['reset_url', 'expires_minutes']
}
```

#### Daily Reminder

```typescript
{
  name: 'daily_reminder',
  type: 'email',
  subject: 'Time for Your Daily Meditation',
  body: `
    <h1>Daily Reminder</h1>
    <p>Hi {{user_name}}, it's time for your meditation.</p>
    <p>Streak: {{streak_days}} days</p>
    <a href="{{session_url}}">Start Session</a>
  `,
  variables: ['user_name', 'streak_days', 'session_url']
}
```

#### Course Completion

```typescript
{
  name: 'course_completion',
  type: 'email',
  subject: 'Congratulations! You Completed {{course_name}}',
  body: `
    <h1>Course Complete!</h1>
    <p>You've finished "{{course_name}}".</p>
    <p>Sessions completed: {{session_count}}</p>
    <a href="{{certificate_url}}">View Certificate</a>
  `,
  variables: ['course_name', 'session_count', 'certificate_url']
}
```

---

## Sending Emails

### Email Message Format

```typescript
interface EmailMessage {
  to: string; // Recipient email
  from?: string; // Sender (uses default if not provided)
  subject: string;
  body: string; // Plain text body
  html?: string; // HTML body
  replyTo?: string;
  attachments?: EmailAttachment[];
  headers?: Record<string, string>;
  trackOpens?: boolean; // Default: true
  trackClicks?: boolean; // Default: true
}

interface EmailAttachment {
  filename: string;
  content: string | Buffer;
  contentType?: string;
  disposition?: 'attachment' | 'inline';
  contentId?: string; // For inline images
}
```

### Basic Email

```typescript
const result = await dispatcher.sendEmail({
  to: 'user@example.com',
  subject: 'Welcome to Lilith',
  body: 'Welcome to your meditation journey!',
  html: '<h1>Welcome</h1><p>Your journey begins...</p>',
});
```

### Email with Template

```typescript
const template = state.templates.get('welcome_email');
const rendered = renderTemplate(template.body, {
  user_name: 'Sarah',
  verify_url: 'https://lilith.app/verify?token=abc123',
});

const result = await dispatcher.sendEmail({
  to: user.email,
  subject: renderTemplate(template.subject, { user_name: 'Sarah' }),
  body: stripHtml(rendered), // Plain text fallback
  html: rendered,
});
```

### Email with Attachments

```typescript
const result = await dispatcher.sendEmail({
  to: 'user@example.com',
  subject: 'Your Certificate',
  body: 'Please find your certificate attached.',
  html: '<p>Please find your certificate attached.</p>',
  attachments: [
    {
      filename: 'certificate.pdf',
      content: pdfBuffer,
      contentType: 'application/pdf',
      disposition: 'attachment',
    },
    {
      filename: 'logo.png',
      content: logoBuffer,
      contentType: 'image/png',
      disposition: 'inline',
      contentId: 'logo', // Reference in HTML as cid:logo
    },
  ],
});
```

### Email with Custom Headers

```typescript
const result = await dispatcher.sendEmail({
  to: 'user@example.com',
  subject: 'Weekly Digest',
  body: 'Your weekly summary...',
  headers: {
    'X-Priority': '3',
    'X-Campaign-ID': 'weekly_digest_2024_01',
    ...generateListUnsubscribeHeader(userId, email, 'email', 'weekly_digest'),
  },
});
```

### Batch Sending

```typescript
// SendGrid batch (parallel)
const results = await sendgridProvider.sendBatch(messages);

// SES batch (rate-limited to 14/second)
const results = await sesProvider.sendBatch(messages);
```

---

## Unsubscribe Handling

### Overview

The unsubscribe system is compliant with:

- **CAN-SPAM Act**: Functional unsubscribe within 10 business days
- **GDPR**: User control over marketing communications
- **RFC 8058**: One-Click List Unsubscribe

### Environment Variables

| Variable                   | Required | Description                    |
| -------------------------- | -------- | ------------------------------ |
| `UNSUBSCRIBE_SECRET_KEY`   | Yes\*    | HMAC secret for signing tokens |
| `NOTIFICATION_SERVICE_URL` | No       | Base URL for unsubscribe links |

\*A default key is used in development/test environments.

### Unsubscribe Token Generation

```typescript
import {
  generateUnsubscribeToken,
  generateUnsubscribeUrl,
  generateListUnsubscribeHeader
} from '@lilith/notification/helpers';

// Generate token
const token = generateUnsubscribeToken(
  userId,
  email,
  'email',           // channel
  'weekly_digest',   // topic (optional)
  30                 // expiry days (default: 30)
);

// Generate full URL
const url = generateUnsubscribeUrl(userId, email, 'email', 'weekly_digest');
// Output: http://localhost:8082/v1/unsubscribe?token=...

// Generate headers for one-click unsubscribe
const headers = generateListUnsubscribeHeader(userId, email, 'email', 'weekly_digest');
// Returns:
{
  'List-Unsubscribe': '<https://...>',
  'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click'
}
```

### Token Validation

```typescript
import { validateUnsubscribeToken } from '@lilith/notification/helpers';

const payload = validateUnsubscribeToken(token);

if (payload) {
  // Valid token
  console.log(payload.user_id, payload.email, payload.topic);
} else {
  // Invalid or expired token
}
```

### Unsubscribe Record

```typescript
interface UnsubscribeRecord {
  id: string;
  user_id: string;
  email: string;
  topic: string | null; // null = global unsubscribe
  scope: 'all' | 'topic';
  reason?: UnsubscribeReason;
  reason_detail?: string;
  channel: 'push' | 'email';
  source: 'one_click' | 'link' | 'manual' | 'admin' | 'bounce' | 'complaint';
  unsubscribed_at: string;
  resubscribed_at: string | null;
  ip_address?: string;
  user_agent?: string;
}

type UnsubscribeReason =
  | 'too_many_emails'
  | 'not_relevant'
  | 'never_signed_up'
  | 'inappropriate_content'
  | 'technical_issues'
  | 'other';
```

### Checking Unsubscribe Status

```typescript
import { isUnsubscribed, getUnsubscribes } from '@lilith/notification/helpers';

// Check if unsubscribed
const unsubscribed = isUnsubscribed(state, email, 'email', 'weekly_digest');

if (unsubscribed) {
  // Skip sending email
  return { skipped: true, reason: 'unsubscribed' };
}

// Get all unsubscribes for an email
const records = getUnsubscribes(state, email, 'email');
```

### Creating Unsubscribe

```typescript
import { createUnsubscribe } from '@lilith/notification/helpers';

const record = createUnsubscribe(
  state,
  userId,
  email,
  'email', // channel
  'one_click', // source
  'weekly_digest', // topic (optional)
  'too_many_emails', // reason (optional)
  'I get too many', // reason_detail (optional)
  '192.168.1.1', // IP address
  'Mozilla/5.0...' // User agent
);
```

### Resubscribe

```typescript
import { processResubscribe } from '@lilith/notification/helpers';

const record = processResubscribe(state, email, 'email', 'weekly_digest');

if (record) {
  console.log('Resubscribed:', record.id);
}
```

### Unsubscribe Statistics

```typescript
import { getUnsubscribeStats } from '@lilith/notification/helpers';

const stats = getUnsubscribeStats(state, 'email');

console.log(stats);
// Output:
{
  totalUnsubscribes: 150,
  activeUnsubscribes: 120,
  resubscribes: 30,
  byReason: {
    'too_many_emails': 80,
    'not_relevant': 40,
    'other': 30
  },
  bySource: {
    'one_click': 100,
    'link': 30,
    'bounce': 20
  },
  byTopic: {
    'weekly_digest': 50,
    'global': 70,
    'promotions': 30
  }
}
```

---

## Bounce & Complaint Handling

### Bounce Types

| Type        | Description     | Action             |
| ----------- | --------------- | ------------------ |
| Hard Bounce | Invalid address | Auto-unsubscribe   |
| Soft Bounce | Temporary issue | Track, retry later |
| Complaint   | Spam report     | Auto-unsubscribe   |

### Auto-Unsubscribe on Bounce

```typescript
// Webhook handler for bounce events
app.post('/webhooks/email/bounce', async (req, reply) => {
  const { email, bounceType, timestamp } = req.body;

  if (bounceType === 'Permanent') {
    // Hard bounce - auto unsubscribe
    createUnsubscribe(
      state,
      '', // Unknown user ID
      email,
      'email',
      'bounce',
      null, // All topics
      'hard_bounce'
    );
  }

  reply.send({ processed: true });
});
```

### Auto-Unsubscribe on Complaint

```typescript
// Webhook handler for complaint events
app.post('/webhooks/email/complaint', async (req, reply) => {
  const { email, complaintFeedbackType } = req.body;

  createUnsubscribe(
    state,
    '',
    email,
    'email',
    'complaint',
    null, // All topics
    'spam_complaint',
    complaintFeedbackType
  );

  reply.send({ processed: true });
});
```

---

## Email Tracking

### SendGrid Tracking

```typescript
const result = await dispatcher.sendEmail({
  to: 'user@example.com',
  subject: 'Hello',
  body: 'Content',
  trackOpens: true, // Track email opens
  trackClicks: true, // Track link clicks
});
```

### SES Configuration Set

Create a configuration set in AWS SES for tracking:

```typescript
const ses = new SESEmailProvider({
  region: 'us-east-1',
  configurationSet: 'lilith-email-tracking',
});
```

Configure SNS topics in AWS for event delivery:

- Bounce
- Complaint
- Delivery
- Open
- Click

---

## Error Handling

### SendGrid Errors

```typescript
const result = await dispatcher.sendEmail(message);

if (!result.success) {
  // SendGrid error details are extracted
  console.error(result.error);
  // Example: "The from address does not match a verified Sender Identity"
}
```

### SES Errors

| Error                                   | Description            | Retryable |
| --------------------------------------- | ---------------------- | --------- |
| `MessageRejected`                       | Email content rejected | No        |
| `ConfigurationSetDoesNotExistException` | Invalid config set     | No        |
| `MailFromDomainNotVerifiedException`    | Sender not verified    | No        |
| `Throttling`                            | Rate limited           | Yes       |
| `ServiceUnavailable`                    | SES unavailable        | Yes       |
| `LimitExceededException`                | Daily limit reached    | Yes       |

---

## SDK Integration

### TypeScript/JavaScript

```typescript
import { LilithClient } from '@lilith/sdk';

const client = new LilithClient({
  apiKey: process.env.LILITH_API_KEY,
});

// Create template
const template = await client.notifications.templates.create({
  name: 'welcome',
  type: 'email',
  subject: 'Welcome!',
  body: '<h1>Welcome {{user_name}}</h1>',
  variables: ['user_name'],
});

// Send email
const result = await client.notifications.email.send({
  userId: 'user_123',
  templateId: template.id,
  variables: { user_name: 'Sarah' },
});

// Get unsubscribe link
const link = await client.notifications.unsubscribe.generateLink({
  userId: 'user_123',
  email: 'user@example.com',
  topic: 'weekly_digest',
});

// Check unsubscribe status
const status = await client.notifications.unsubscribe.check({
  email: 'user@example.com',
  channel: 'email',
  topic: 'weekly_digest',
});

// Unsubscribe
await client.notifications.unsubscribe.unsubscribe({
  email: 'user@example.com',
  channel: 'email',
  topic: 'weekly_digest',
  reason: 'too_many_emails',
});

// Resubscribe
await client.notifications.unsubscribe.resubscribe({
  email: 'user@example.com',
  channel: 'email',
  topic: 'weekly_digest',
});
```

### Adding Unsubscribe to All Emails

```typescript
async function sendMarketingEmail(
  userId: string,
  email: string,
  template: NotificationTemplate
) {
  // Check unsubscribe status first
  if (isUnsubscribed(state, email, 'email', template.name)) {
    return { skipped: true, reason: 'unsubscribed' };
  }

  // Generate unsubscribe header
  const unsubscribeHeaders = generateListUnsubscribeHeader(
    userId,
    email,
    'email',
    template.name
  );

  // Generate unsubscribe link for email footer
  const unsubscribeUrl = generateUnsubscribeUrl(
    userId,
    email,
    'email',
    template.name
  );

  // Render template with unsubscribe link
  const rendered = renderTemplate(template.body, {
    ...variables,
    unsubscribe_url: unsubscribeUrl,
  });

  return dispatcher.sendEmail({
    to: email,
    subject: template.subject,
    body: stripHtml(rendered),
    html: rendered,
    headers: unsubscribeHeaders,
  });
}
```

---

## Best Practices

### Email Deliverability

1. **Verify sender domains**: SPF, DKIM, DMARC records
2. **Use consistent sender**: Same From address builds reputation
3. **Warm up IP addresses**: Gradually increase volume
4. **Monitor bounce rates**: Keep under 2%

### Unsubscribe Compliance

1. **One-click unsubscribe**: Always include List-Unsubscribe header
2. **Honor requests immediately**: Don't send after unsubscribe
3. **Easy to find**: Unsubscribe link clearly visible
4. **No re-opt-in tricks**: Don't send "we miss you" emails

### Template Design

1. **Plain text fallback**: Always include body (not just html)
2. **Mobile responsive**: Test on mobile devices
3. **Accessible**: Alt text, proper contrast
4. **Preview text**: First 50-100 characters matter

---

## Related Documentation

- [Push Notifications](./push-notifications.md) - Push notification setup
- [Notification Preferences](./notification-preferences.md) - User preferences
- [WebSocket API](./websocket-api.md) - Real-time notifications

---

## Questions?

- **Technical Support**: api-support@lilith.app
- **Documentation**: [GitHub Issues](https://github.com/lilith/platform/issues)
