# Email Template

## Email Template Management

Email templates allow you to create reusable email content with dynamic variables that can be customized for each recipient.

### Overview

The template system supports:

* **HTML and Text Content**: Rich HTML emails with optional plain text fallbacks
* **Dynamic Variables**: Personalize emails with user-specific data
* **Template Types**: Organize templates by purpose (welcome, password\_reset, etc.)
* **Active/Inactive Status**: Control which templates are available for use

### Creating Templates

#### Step 1: Access Template Manager

1. Navigate to **Admin Dashboard → Settings → Email System**
2. Click on the **Templates** tab
3. Click **"New Template"** button

#### Step 2: Configure Template Details

**Template Type**: A unique identifier for the template (e.g., `welcome_email`, `password_reset`)

* Use lowercase with underscores
* Must be unique across all templates
* Used when calling the email service API

**Subject**: The email subject line

* Can include variables using `{{variable_name}}` syntax
* Example: `Welcome to {{dao_name}}, {{user_name}}!`

#### Step 3: Create Email Content

**HTML Content**: The main email body with rich formatting

```html
<h1>Welcome to Treem DAO, {{user_name}}!</h1>
<p>Thank you for joining our community. Your account has been successfully created.</p>
<p>You can now access your dashboard at: <a href="{{dashboard_url}}">{{dashboard_url}}</a></p>
<p>Best regards,<br>The Treem DAO Team</p>
```

**Text Content** (Optional): Plain text version for email clients that don't support HTML

```
Welcome to Treem DAO, {{user_name}}!

Thank you for joining our community. Your account has been successfully created.

You can now access your dashboard at: {{dashboard_url}}

Best regards,
The Treem DAO Team
```

#### Step 4: Define Variables

**Variables**: Comma-separated list of variables used in the template

* Example: `user_name, dao_name, dashboard_url`
* Variables are automatically detected from your content
* Used for validation when sending emails

#### Step 5: Set Status

**Active**: Enable or disable the template

* Only active templates can be used for sending emails
* Inactive templates are preserved but not available for selection

### Template Variables

#### Common Variables

| Variable        | Description             | Example                                      |
| --------------- | ----------------------- | -------------------------------------------- |
| `user_name`     | User's display name     | John Doe                                     |
| `user_email`    | User's email address    | <john@example.com>                           |
| `dao_name`      | DAO organization name   | Treem DAO                                    |
| `dashboard_url` | Link to user dashboard  | <https://app.treemdao.com/dashboard>         |
| `confirm_url`   | Email confirmation link | <https://app.treemdao.com/confirm?token=>... |
| `reset_url`     | Password reset link     | <https://app.treemdao.com/reset?token=>...   |

#### Custom Variables

You can define custom variables for specific use cases:

* `proposal_title` - For governance notifications
* `transaction_amount` - For payment confirmations
* `event_date` - For event reminders
* `stake_amount` - For staking notifications

### Template Types

#### System Templates

**welcome\_email**: Sent when users first join the DAO

* Variables: `user_name`, `dao_name`, `dashboard_url`

**password\_reset**: Sent when users request password reset

* Variables: `user_name`, `reset_url`, `expiry_time`

**email\_confirmation**: Sent to verify email addresses

* Variables: `user_name`, `confirm_url`

#### Governance Templates

**new\_proposal**: Notify users about new proposals

* Variables: `user_name`, `proposal_title`, `proposal_url`, `voting_deadline`

**voting\_reminder**: Remind users to vote on active proposals

* Variables: `user_name`, `proposal_title`, `days_remaining`, `vote_url`

#### Transaction Templates

**purchase\_confirmation**: Confirm token purchases

* Variables: `user_name`, `token_amount`, `total_cost`, `transaction_id`

**staking\_confirmation**: Confirm staking transactions

* Variables: `user_name`, `stake_amount`, `lock_period`, `unlock_date`

### Managing Templates

#### Editing Templates

1. Click the **Edit** icon on any template
2. Modify the template content
3. Update variables if needed
4. Click **"Update Template"**

#### Previewing Templates

1. Click the **Preview** icon on any template
2. View the rendered HTML content
3. Check the plain text version
4. Review variable usage

#### Deleting Templates

1. Click the **Delete** icon on any template
2. Confirm the deletion
3. **Warning**: This action cannot be undone

### Best Practices

#### Content Guidelines

1. **Keep it concise**: Users prefer shorter emails
2. **Clear call-to-action**: Make it obvious what users should do next
3. **Mobile-friendly**: Use responsive HTML design
4. **Brand consistency**: Match your DAO's visual identity

#### Variable Usage

1. **Always provide fallbacks**: Handle cases where variables might be empty
2. **Validate variables**: Ensure all template variables are provided when sending
3. **Use descriptive names**: Make variable purposes clear
4. **Document custom variables**: Keep track of what each variable represents

#### HTML Best Practices

1. **Use table-based layouts**: Better email client compatibility
2. **Inline CSS**: Many email clients strip external stylesheets
3. **Test across clients**: Email rendering varies significantly
4. **Include alt text**: For images and accessibility

### Integration with Bulk Sending

Templates integrate seamlessly with the bulk email sender:

1. Select your template from the dropdown
2. Fill in the required variables
3. Choose your recipient groups
4. Send to multiple users at once

### API Integration

Templates can be used programmatically via the enhanced-email-service:

```javascript
const { data, error } = await supabase.functions.invoke('enhanced-email-service', {
  body: {
    template_type: 'welcome_email',
    recipient_email: 'user@example.com',
    variables: {
      user_name: 'John Doe',
      dao_name: 'Treem DAO',
      dashboard_url: 'https://app.treemdao.com/dashboard'
    }
  }
});
```

### Troubleshooting

#### Template Not Available for Selection

* Check if the template is marked as **Active**
* Verify the template\_type is unique
* Ensure all required fields are filled

#### Variables Not Replacing

* Check variable names match exactly (case-sensitive)
* Ensure variables are defined in the template configuration
* Verify variable syntax uses `{{variable_name}}` format

#### HTML Not Rendering

* Test HTML in the preview function
* Check for unclosed tags or invalid markup
* Ensure proper email-safe HTML structure
