← back to Dear Bubbe Nextjs

docs/EMAIL_SYSTEM.md

252 lines

# Dear Bubbe Email System Documentation

## Overview
The Dear Bubbe email system sends beautiful, personalized welcome emails to new users after they complete onboarding. Since we don't have a real email service configured yet, emails are saved locally for testing and review.

## Features

### 1. Welcome Email Template
- **Beautiful HTML design** with Bubbe branding
- **Personalized content** based on user profile (location, relationship status, kids)
- **Responsive layout** that works on all devices
- **Plain text fallback** for email clients that don't support HTML
- **Yiddish glossary** to help new users understand Bubbe's language
- **Clear terms reminder** about zero-tolerance policy for offensive language

### 2. Email Content Includes
- Warm welcome message from Bubbe
- Personalized observations about user's profile
- List of features (weather, news, sports, advice)
- Important zero-tolerance policy notice
- Yiddish glossary for common terms
- Links to terms, privacy, and support
- Call-to-action button to start chatting

## API Endpoints

### POST /api/send-welcome-email
Sends a welcome email to a new user.

**Request Body:**
```json
{
  "to": "user@example.com",
  "name": "User Name",
  "userId": "user-123",
  "profile": {
    "location": "Brooklyn, NY",
    "relationshipStatus": "single",
    "hasKids": "no",
    "religiousLevel": "somewhat"
  }
}
```

**Response:**
```json
{
  "success": true,
  "message": "Welcome email sent successfully",
  "emailId": "email-1234567890",
  "to": "user@example.com"
}
```

### GET /api/send-welcome-email
Retrieves email history.

**Query Parameters:**
- `email` (optional) - Filter by recipient email address

**Response:**
```json
{
  "success": true,
  "count": 5,
  "emails": [
    {
      "id": "email-123",
      "type": "welcome",
      "to": "user@example.com",
      "subject": "Welcome to Dear Bubbe...",
      "sentAt": "2024-11-19T...",
      "status": "sent",
      "htmlLength": 15234
    }
  ]
}
```

## File Structure

```
/root/Projects/dear-bubbe-nextjs/
├── app/api/send-welcome-email/
│   └── route.ts              # API endpoint handler
├── lib/email-templates/
│   └── welcome.ts            # Email template generator
├── data/emails/              # Stored email records
│   └── welcome-*.json        # Individual email files
├── test-email.js             # Test script for email system
└── view-emails.js            # Utility to view saved emails
```

## Testing

### 1. Run Test Script
```bash
cd /root/Projects/dear-bubbe-nextjs
node test-email.js
```

This will:
- Send a test welcome email
- Retrieve email history
- Test error handling
- Save emails to /data/emails/

### 2. View Saved Emails
```bash
# List all emails
node view-emails.js

# Show latest email content
node view-emails.js -s

# Show email statistics
node view-emails.js --stats
```

### 3. Manual Testing
1. Complete the onboarding process as a new user
2. Check console logs for email sending confirmation
3. View saved email in `/data/emails/` directory
4. Open HTML file in browser to see formatted version

## Integration Points

### 1. Onboarding Flow (page.tsx)
The email is automatically sent after successful profile save:
```javascript
// After profile saved successfully
const emailResponse = await fetch('/api/send-welcome-email', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    to: session.user?.email,
    name: session.user?.name,
    userId: session.userId,
    profile: savedProfile
  })
})
```

### 2. Email Storage
Emails are stored as JSON files with the naming format:
```
welcome-[timestamp]-[email].json
```

Example: `welcome-2024-11-19T12-30-45-123Z-user_at_example.com.json`

## Email Template Variables

The welcome email template uses these profile variables:
- `name` - User's name (defaults to "Bubbeleh")
- `email` - User's email address
- `location` - User's location for localized content
- `relationshipStatus` - Personalized relationship commentary
- `hasKids` - Personalized kids commentary
- `religiousLevel` - Not currently used but available

## Production Deployment

To enable real email sending in production:

1. **Choose an email service provider:**
   - SendGrid
   - AWS SES
   - Mailgun
   - Postmark

2. **Install the provider's SDK:**
   ```bash
   npm install @sendgrid/mail
   # or
   npm install aws-sdk
   ```

3. **Update the API route** to use real email service:
   ```javascript
   // Replace mockSendEmail with real service
   import sgMail from '@sendgrid/mail'
   sgMail.setApiKey(process.env.SENDGRID_API_KEY)
   await sgMail.send(emailData)
   ```

4. **Add environment variables:**
   ```env
   SENDGRID_API_KEY=your-api-key
   FROM_EMAIL=bubbe@bubbe.ai
   ```

## Security Considerations

1. **Email validation** - Always validate email addresses
2. **Rate limiting** - Implement rate limiting to prevent abuse
3. **Authentication** - Ensure only authenticated users trigger emails
4. **Content sanitization** - Sanitize any user-provided content
5. **GDPR compliance** - Include unsubscribe links in production

## Monitoring

### Logs to Monitor
- `[EMAIL]` - Email sending operations
- `[ONBOARDING]` - Onboarding completion and email triggers
- Error logs for failed email sends

### Metrics to Track
- Total emails sent
- Email send success rate
- Average email size
- Most common failure reasons

## Troubleshooting

### Email not sending after onboarding
1. Check console logs for errors
2. Verify user has email address in session
3. Check `/data/emails/` directory for saved files
4. Run test script to verify API works

### Email content incorrect
1. Check user profile data is complete
2. Verify template variables are passed correctly
3. Test with different profile combinations

### Performance issues
1. Implement email queue for async sending
2. Use background jobs for large email batches
3. Optimize HTML template size

## Future Enhancements

1. **Additional Email Types:**
   - Daily digest emails
   - Reminder emails for inactive users
   - Special occasion emails (holidays, birthdays)

2. **Personalization:**
   - A/B testing different subject lines
   - Dynamic content based on user behavior
   - Localized content for different regions

3. **Analytics:**
   - Email open tracking
   - Click-through rates
   - Conversion tracking

4. **Automation:**
   - Drip campaigns for new users
   - Re-engagement campaigns
   - Referral program emails