## SMTP Email Integration Guide

This guide explains how to set up email sending using Gmail SMTP.

### Prerequisites
- Gmail account
- Application-specific password enabled

### Step 1: Enable 2-Factor Authentication on Gmail

1. Go to: https://myaccount.google.com/security
2. Look for "2-Step Verification"
3. Follow the steps to enable 2FA

### Step 2: Create App Password

1. Go to: https://myaccount.google.com/apppasswords
2. Select:
   - Mail
   - Windows Computer (or your OS)
3. Google will generate a 16-character password
4. Copy this password (you'll need it for .env)

### Step 3: Get SMTP Credentials

**For Gmail:**
- SMTP Server: smtp.gmail.com
- Port: 587 (TLS) or 465 (SSL)
- Username: your-email@gmail.com
- Password: Your App Password (from Step 2)

**For Other Email Providers:**

**Microsoft Outlook:**
- SMTP: smtp.office365.com
- Port: 587
- Username: your-email@outlook.com
- Password: Your account password

**SendGrid (Recommended for Production):**
- SMTP: smtp.sendgrid.net
- Port: 587
- Username: apikey
- Password: Your SendGrid API key

### Step 4: Configure .env

In `backend/.env`, add:

```env
# Gmail Example
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=xxxx xxxx xxxx xxxx
SMTP_FROM=Trust Tax Advisor <your-email@gmail.com>
```

### Step 5: Test Email Sending

```javascript
import { sendEmail } from './config/email.js';

const result = await sendEmail(
  'recipient@example.com',
  'Test Subject',
  '<h1>Hello!</h1><p>This is a test email.</p>'
);

console.log(result); // { success: true, messageId: '...' }
```

### Email Templates

#### OTP Email Template
```html
<html>
  <body style="font-family: Arial, sans-serif;">
    <h2>Your OTP Code</h2>
    <p>Your OTP is: <strong>123456</strong></p>
    <p>Valid for 10 minutes.</p>
    <p style="color: #666; font-size: 12px;">
      If you didn't request this, please ignore.
    </p>
  </body>
</html>
```

#### Order Confirmation Email Template
```html
<html>
  <body style="font-family: Arial, sans-serif;">
    <h2>Order Confirmation</h2>
    <p>Your order has been received!</p>
    <p><strong>Order ID:</strong> #12345</p>
    <p><strong>Amount:</strong> ₹5000</p>
    <p><strong>Status:</strong> Processing</p>
    <p>We'll send you updates via email and WhatsApp.</p>
  </body>
</html>
```

#### Commission Notification Email
```html
<html>
  <body style="font-family: Arial, sans-serif;">
    <h2>Commission Earned</h2>
    <p>A new commission has been added to your account!</p>
    <p><strong>Order:</strong> #12345</p>
    <p><strong>Amount:</strong> ₹2500</p>
    <p><strong>Status:</strong> Pending</p>
    <p>Log in to view your earnings dashboard.</p>
  </body>
</html>
```

### Integration Examples

**Backend - Send OTP via Email**
```javascript
async sendOtpEmail(email, otp) {
  const htmlContent = `
    <h2>Your OTP is: ${otp}</h2>
    <p>Valid for 10 minutes</p>
  `;
  return await sendEmail(email, 'OTP - Trust Tax Advisor', htmlContent);
}
```

**Backend - Send Order Notification**
```javascript
async notifyOrderCreated(clientEmail, order) {
  const htmlContent = `
    <h2>Order #${order.id} Created</h2>
    <p>Amount: ₹${order.amount}</p>
    <p>Service: ${order.service_name}</p>
  `;
  return await sendEmail(clientEmail, 'Order Confirmation', htmlContent);
}
```

**Backend - Notify Connector of Commission**
```javascript
async notifyCommission(connectorEmail, commission) {
  const htmlContent = `
    <h2>Commission Earned!</h2>
    <p>Amount: ₹${commission.amount}</p>
    <p>Order: #${commission.order_id}</p>
    <p>Status: ${commission.status}</p>
  `;
  return await sendEmail(connectorEmail, 'New Commission', htmlContent);
}
```

### Bulk Email Tips

For sending emails to multiple recipients:

```javascript
async sendBulkEmails(recipients, subject, htmlContent) {
  // Add delay to avoid rate limiting
  for (const email of recipients) {
    await sendEmail(email, subject, htmlContent);
    await new Promise(resolve => setTimeout(resolve, 500)); // 500ms delay
  }
}
```

### Production Best Practices

1. **Use SendGrid or AWS SES**
   - Better deliverability
   - Better reporting
   - Scaled for high volume

2. **Email Queue System**
   - Use Bull/Kue for email jobs
   - Retry failed emails
   - Monitor delivery status

3. **Track Email Opens**
   - Add tracking pixels
   - Monitor click-throughs
   - Improve templates based on analytics

4. **SPF/DKIM Records**
   - Add SPF record to DNS
   - Add DKIM signatures
   - Improve email authentication

### Troubleshooting

**"Invalid login credentials" error**
- Verify Gmail has 2FA enabled
- Check App Password is correct
- Don't use regular Gmail password

**"SMTP connection failed"**
- Check internet connection
- Verify SMTP server address
- Try different port (587 vs 465)
- Check firewall rules

**Emails going to Spam**
- Add SPF record: `v=spf1 include:gmail.com ~all`
- Add DKIM signature
- Use branded email address
- Test with MXToolbox

**"Too many emails" rate limit**
- Gmail: 30 emails per second per account
- Add delays between emails
- Use queue system

### Testing Checklist
- [ ] 2-Factor Authentication enabled on Gmail
- [ ] App Password generated
- [ ] SMTP credentials configured in .env
- [ ] Test email sent successfully
- [ ] HTML templates created
- [ ] Email appears in recipient inbox
- [ ] Check spam/junk folder

### Sample Email Service Code

```javascript
// backend/services/emailService.js
import { sendEmail } from '../config/email.js';

export const EmailService = {
  async sendOTP(email, otp) {
    const html = `<h2>OTP: ${otp}</h2><p>Valid for 10 mins</p>`;
    return sendEmail(email, 'OTP Code', html);
  },

  async sendOrderConfirmation(email, order) {
    const html = `
      <h2>Order Confirmed</h2>
      <p>Order ID: #${order.id}</p>
      <p>Amount: ₹${order.amount}</p>
    `;
    return sendEmail(email, 'Order Confirmation', html);
  },

  async sendCommissionAlert(email, commission) {
    const html = `
      <h2>New Commission</h2>
      <p>Amount: ₹${commission.amount}</p>
      <p>Order: #${commission.order_id}</p>
    `;
    return sendEmail(email, 'Commission Earned', html);
  }
};
```
