# Email Configuration Guide

## Overview
The Brand Master application supports sending transactional emails for:
- Password reset PINs
- Welcome emails for new users
- Order confirmations (future)
- Contact form notifications (future)

## Email Service Options

### Option 1: Gmail SMTP (Recommended for Testing)

1. **Create App Password** (if using Gmail with 2FA):
   - Go to Google Account Settings → Security
   - Enable 2-Factor Authentication
   - Go to "App passwords"
   - Generate app password for "Mail"
   - Copy the 16-character password

2. **Configure Environment Variables**:
   ```bash
   SMTP_HOST=smtp.gmail.com
   SMTP_PORT=587
   SMTP_USERNAME=your-email@gmail.com
   SMTP_PASSWORD=your-app-password
   SMTP_FROM=noreply@brand-master.com
   ```

### Option 2: SendGrid (Recommended for Production)

1. **Create SendGrid Account**:
   - Sign up at https://sendgrid.com
   - Verify your sender email
   - Create API key

2. **Configure Environment Variables**:
   ```bash
   SMTP_HOST=smtp.sendgrid.net
   SMTP_PORT=587
   SMTP_USERNAME=apikey
   SMTP_PASSWORD=your-sendgrid-api-key
   SMTP_FROM=noreply@brand-master.com
   ```

### Option 3: Amazon SES (Production - Most Reliable)

1. **Setup SES**:
   - Sign up for AWS SES
   - Verify your domain or email
   - Get SMTP credentials

2. **Configure Environment Variables**:
   ```bash
   SMTP_HOST=email-smtp.us-east-1.amazonaws.com
   SMTP_PORT=587
   SMTP_USERNAME=your-ses-smtp-username
   SMTP_PASSWORD=your-ses-smtp-password
   SMTP_FROM=noreply@brand-master.com
   ```

## Kubernetes Deployment Configuration

### Method 1: Update values.yaml (Recommended)

Edit `brand-master-chart/values.yaml`:

```yaml
backend:
  env:
    # Existing vars...
    - name: SMTP_HOST
      value: "smtp.gmail.com"
    - name: SMTP_PORT
      value: "587"
    - name: SMTP_USERNAME
      value: "your-email@gmail.com"
    - name: SMTP_PASSWORD
      value: "your-app-password"  # Use secrets in production!
    - name: SMTP_FROM
      value: "noreply@brand-master.com"
```

### Method 2: Use Kubernetes Secret (Production)

1. **Create Secret**:
   ```bash
   kubectl create secret generic brand-master-email \
     --from-literal=smtp-username=your-email@gmail.com \
     --from-literal=smtp-password=your-app-password \
     -n my-apps
   ```

2. **Update Deployment** (`brand-master-chart/templates/backend-deployment.yaml`):
   ```yaml
   env:
     # ... existing env vars ...
     - name: SMTP_HOST
       value: "smtp.gmail.com"
     - name: SMTP_PORT
       value: "587"
     - name: SMTP_USERNAME
       valueFrom:
         secretKeyRef:
           name: brand-master-email
           key: smtp-username
     - name: SMTP_PASSWORD
       valueFrom:
         secretKeyRef:
           name: brand-master-email
           key: smtp-password
     - name: SMTP_FROM
       value: "noreply@brand-master.com"
   ```

## Local Development (.env file)

Create `backend/.env`:

```env
DATABASE_URL=postgresql://brand_master_user:your_password@localhost/brand_master_db
JWT_SECRET_KEY=your-secret-key
FRONTEND_URL=http://localhost:5173
BACKEND_URL=http://localhost:8000

# Email Configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=your-email@gmail.com
SMTP_PASSWORD=your-app-password
SMTP_FROM=noreply@brand-master.com

# Admin Credentials
ADMIN_EMAIL=admin@brandmaster.com
ADMIN_PASSWORD=Admin123!
```

## Testing Email Functionality

### Test Password Reset

1. **Trigger Password Reset**:
   ```bash
   curl -X POST https://api-brand-master.dvirlabs.com/api/auth/request-reset-pin \
     -H "Content-Type: application/json" \
     -d '{"email": "user@example.com"}'
   ```

2. **Check Email**:
   - User should receive email with 6-digit PIN
   - PIN expires in 15 minutes

3. **Reset Password**:
   ```bash
   curl -X POST https://api-brand-master.dvirlabs.com/api/auth/reset-password-with-pin \
     -H "Content-Type: application/json" \
     -d '{
       "email": "user@example.com",
       "pin": "123456",
       "new_password": "NewPassword123!"
     }'
   ```

### Test Welcome Email

1. **Register New User**:
   ```bash
   curl -X POST https://api-brand-master.dvirlabs.com/api/auth/register \
     -H "Content-Type: application/json" \
     -d '{
       "email": "newuser@example.com",
       "full_name": "Test User",
       "password": "password123"
     }'
   ```

2. **Check Email**:
   - User should receive welcome email

### Check Backend Logs

If emails aren't being sent:

```bash
# View backend logs
kubectl logs -n my-apps deployment/brand-master-backend -f

# Look for:
# ✅ Email sent successfully to user@example.com
# OR
# ⚠️ SMTP not configured. Email would have been sent to: user@example.com
# OR
# ❌ Failed to send email to user@example.com: <error details>
```

## Troubleshooting

### Issue: "SMTP not configured" message

**Problem**: SMTP environment variables not set

**Solution**:
```bash
# Check if variables are set in pod
kubectl exec -n my-apps deployment/brand-master-backend -- env | grep SMTP

# Should show:
# SMTP_HOST=smtp.gmail.com
# SMTP_PORT=587
# SMTP_USERNAME=your-email@gmail.com
# SMTP_PASSWORD=***
# SMTP_FROM=noreply@brand-master.com
```

### Issue: "Authentication failed" error

**Problem**: Wrong credentials or app password required

**Solution**:
- For Gmail: Use App Password, not account password
- Verify credentials are correct
- Check if 2FA is enabled (required for App Passwords)

### Issue: "Connection refused" error

**Problem**: Wrong SMTP host or port, or firewall blocking

**Solution**:
- Verify SMTP_HOST and SMTP_PORT are correct
- Check Kubernetes network policies
- Test SMTP connection from pod:
  ```bash
  kubectl exec -n my-apps deployment/brand-master-backend -- \
    nc -zv smtp.gmail.com 587
  ```

### Issue: Emails go to spam

**Problem**: Missing SPF/DKIM records or sender reputation

**Solution**:
- Use verified domain with proper DNS records
- Use SendGrid or SES for production
- Add SPF record: `v=spf1 include:_spf.google.com ~all`
- Setup DKIM signing

## Email Templates

Email templates are in `backend/app/services/email.py`:

- `send_password_reset_pin()` - Password reset with PIN
- `send_welcome_email()` - Welcome new users

To customize:
1. Edit template in `email.py`
2. Rebuild backend image
3. Redeploy

## Production Best Practices

1. ✅ **Use Kubernetes Secrets** for credentials
2. ✅ **Use dedicated email service** (SendGrid, SES)
3. ✅ **Setup SPF/DKIM** for deliverability
4. ✅ **Monitor email sending** (logs, metrics)
5. ✅ **Implement rate limiting** to prevent abuse
6. ✅ **Use verified sender domain**
7. ✅ **Add unsubscribe links** for marketing emails
8. ✅ **Keep templates professional** and branded

## Quick Setup for Testing (Gmail)

```bash
# 1. Update values.yaml
nano brand-master-chart/values.yaml

# Add under backend.env:
    - name: SMTP_HOST
      value: "smtp.gmail.com"
    - name: SMTP_PORT
      value: "587"
    - name: SMTP_USERNAME
      value: "your-email@gmail.com"
    - name: SMTP_PASSWORD
      value: "your-16-char-app-password"
    - name: SMTP_FROM
      value: "Brand Master <noreply@brand-master.com>"

# 2. Redeploy
cd brand-master-chart
helm upgrade brand-master . --namespace my-apps --wait

# 3. Test
curl -X POST https://api-brand-master.dvirlabs.com/api/auth/request-reset-pin \
  -H "Content-Type: application/json" \
  -d '{"email": "your-test-email@gmail.com"}'

# 4. Check email inbox
```

## Support

If emails still don't work:
1. Check backend logs for error messages
2. Verify SMTP credentials
3. Test SMTP connection manually
4. Check spam folder
5. Try different email provider

---

**Status**: Email service implemented and ready to configure  
**Last Updated**: May 8, 2026
