# Email Setup Guide

This guide will help you configure the email functionality for the Caravan Builder application.

## Overview

The email system sends two emails when a customer submits their caravan specification:
1. **Customer Email**: A beautifully formatted email with their custom build summary
2. **Admin Email**: A notification to the admin with customer contact details

## Quick Setup

### 1. Install Dependencies

```bash
npm install nodemailer
```

### 2. Configure Environment Variables

Copy `.env.example` to `.env` and update the following variables:

```env
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=your-email@gmail.com
EMAIL_PASSWORD=your-app-password
EMAIL_FROM=your-email@gmail.com
ADMIN_EMAIL=admin@example.com
```

### 3. Email Provider Setup

#### Gmail Setup (Recommended for Development)

1. Go to your Google Account settings
2. Enable 2-Step Verification
3. Generate an App Password:
   - Visit: https://myaccount.google.com/apppasswords
   - Select "Mail" and your device
   - Copy the 16-character password
   - Use this as `EMAIL_PASSWORD` in `.env`

**Important**: Never use your actual Gmail password. Always use App Passwords.

#### Other Email Providers

**Outlook/Hotmail:**
```env
EMAIL_HOST=smtp-mail.outlook.com
EMAIL_PORT=587
EMAIL_SECURE=false
```

**Yahoo:**
```env
EMAIL_HOST=smtp.mail.yahoo.com
EMAIL_PORT=587
EMAIL_SECURE=false
```

**SendGrid (Recommended for Production):**
```env
EMAIL_HOST=smtp.sendgrid.net
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=apikey
EMAIL_PASSWORD=your-sendgrid-api-key
```

### 4. Test the Setup

Start your backend server:
```bash
npm start
```

The API endpoint is available at:
```
POST http://localhost:8000/api/send-email
```

## API Usage

### Request Format

```javascript
{
  "formData": {
    "fullName": "John Doe",
    "email": "customer@example.com",
    "phoneNumber": "+1234567890",
    "state": "California",
    "postCode": "90210",
    // Optional fields
    "intendedTowVehicle": "Ford F-150",
    "towCapacity": "3500kg",
    "travelType": "Off-road",
    "deliveryTime": "3 months"
  },
  "caravanSummary": "<table>...</table>", // HTML content
  "caravanName": "Explorer 4x4",
  "manufacturerName": "Acme Caravans"
}
```

### Response Format

**Success:**
```javascript
{
  "success": true,
  "message": "Emails sent successfully",
  "data": {
    "customerEmailSent": true,
    "adminEmailSent": true
  }
}
```

**Error:**
```javascript
{
  "success": false,
  "message": "Failed to send email",
  "error": "Error details..."
}
```

## Email Templates

### Customer Email
- Professional header with caravan name
- Personalized greeting
- Complete caravan specification summary (HTML table)
- Contact information footer

### Admin Email
- Customer contact details
- All form data (mandatory + optional fields)
- Submission timestamp
- Reply-to set to customer's email for easy response

## Troubleshooting

### Common Issues

**1. Authentication Failed**
- Verify email credentials are correct
- For Gmail: Ensure you're using an App Password, not your regular password
- Check if 2-Factor Authentication is enabled (required for Gmail App Passwords)

**2. Connection Timeout**
- Verify EMAIL_HOST and EMAIL_PORT are correct
- Check firewall settings
- Some ISPs block SMTP ports (try port 465 with EMAIL_SECURE=true)

**3. Emails Going to Spam**
- Add SPF and DKIM records to your domain (production)
- Use a dedicated email service like SendGrid or AWS SES
- Ensure FROM address matches your domain

**4. Missing Environment Variables**
```
Error: Missing required environment variables
```
- Check all EMAIL_* variables are set in `.env`
- Restart the server after updating `.env`

### Debug Mode

Enable detailed logging by checking server console for:
```
Customer email sent: <messageId>
Admin email sent: <messageId>
```

## Production Recommendations

1. **Use a Dedicated Email Service**
   - SendGrid (99 emails/day free)
   - AWS SES (62,000 emails/month free)
   - Mailgun
   - Postmark

2. **Security**
   - Never commit `.env` file to version control
   - Use environment variables in production
   - Rotate credentials regularly

3. **Monitoring**
   - Track email delivery rates
   - Monitor bounce rates
   - Set up alerts for failed sends

4. **Rate Limiting**
   - Implement rate limiting on the endpoint
   - Add CAPTCHA for public forms
   - Monitor for abuse

## Frontend Integration

The TowingForm component automatically calls the email API when:
- User clicks "Download My Spec" (sends all form data)
- User clicks "Skip and Download" (sends only mandatory fields)

Both actions also trigger a PDF download before sending the email.

## Support

For issues or questions:
1. Check server logs for error messages
2. Verify email credentials
3. Test with a different email provider
4. Check firewall/network settings
