# Enhanced Email Configuration Examples

This directory contains examples demonstrating the improved email functionality in pdf-reporter v1.0.3+.

## New Features

### 1. Smart SMTP Configuration Defaults

The library now automatically applies optimal SMTP settings based on the email provider:

```javascript
const config = {
  to: 'recipient@example.com',
  smtp: {
    host: 'smtp.gmail.com',
    // port and secure will be auto-configured to 587 and false
    auth: { user: 'user@gmail.com', pass: 'app-password' }
  }
};

// Apply smart defaults
applySmartEmailDefaults(config);
console.log(config.smtp); 
// { host: 'smtp.gmail.com', port: 587, secure: false, auth: {...} }
```

**Supported Providers:**
- Gmail: `port: 587, secure: false`
- Outlook/Office365: `port: 587, secure: false`
- Yahoo: `port: 587, secure: false`
- SendGrid: `port: 587, secure: false`
- Mailgun: `port: 587, secure: false`

### 2. Enhanced SMTP Validation

Prevents common misconfigurations and provides helpful error messages:

```javascript
// This will throw a helpful error
const badConfig = {
  smtp: {
    host: 'smtp.gmail.com',
    port: 465,
    secure: false  // Error: Port 465 requires secure=true
  }
};

validateEmailConfig(badConfig); // Throws descriptive error
```

### 3. Auto-Correction

Automatically fixes common mistakes:

```javascript
const config = {
  smtp: {
    host: 'smtp.gmail.com',
    port: 465
    // secure is undefined - will be auto-corrected to true
  }
};

validateEmailConfig(config);
// Console: "Auto-corrected: Port 465 detected, setting secure=true"
```

### 4. Connection Testing

Test email configuration before sending:

```javascript
const testResult = await testEmailConnection(emailConfig);

if (testResult.success) {
  console.log('✅ Connection successful');
  console.log('Provider:', testResult.details.provider);
} else {
  console.log('❌ Connection failed:', testResult.error);
}
```

### 5. Enhanced Error Messages

Better error messages help diagnose issues:

```javascript
// Before: "Error: socket close"
// After: "Email sending failed: Unexpected socket close. This usually indicates 
//        SMTP port/security mismatch. Current config: smtp.gmail.com:465 
//        (secure=false). For Gmail: Use port 587 with secure=false, or 
//        port 465 with secure=true."
```

## Running the Examples

```bash
cd examples/email-configuration
node email-examples.js
```

The examples will demonstrate:
- Smart defaults application
- Configuration validation
- Auto-correction features
- Error handling improvements

## Common Email Provider Configurations

### Gmail
```javascript
{
  smtp: {
    host: 'smtp.gmail.com',
    port: 587,
    secure: false,
    auth: {
      user: 'your-email@gmail.com',
      pass: 'your-app-password'  // Use App Password, not regular password
    }
  }
}
```

### Outlook/Office365
```javascript
{
  smtp: {
    host: 'smtp.outlook.com',  // or smtp.office365.com
    port: 587,
    secure: false,
    auth: {
      user: 'your-email@outlook.com',
      pass: 'your-password'
    }
  }
}
```

### Yahoo
```javascript
{
  smtp: {
    host: 'smtp.mail.yahoo.com',
    port: 587,
    secure: false,
    auth: {
      user: 'your-email@yahoo.com',
      pass: 'your-app-password'  // Use App Password
    }
  }
}
```

### SendGrid
```javascript
{
  smtp: {
    host: 'smtp.sendgrid.net',
    port: 587,
    secure: false,
    auth: {
      user: 'apikey',
      pass: 'your-sendgrid-api-key'
    }
  }
}
```

## Migration Guide

If you're upgrading from an older version:

1. **No breaking changes** - existing configurations continue to work
2. **Smart defaults** are applied automatically when missing
3. **Auto-correction** happens during validation
4. **Enhanced errors** provide better debugging information

### Before (v1.0.2 and earlier)
```javascript
// You had to manually specify all SMTP settings
const emailConfig = {
  to: 'user@example.com',
  smtp: {
    host: 'smtp.gmail.com',
    port: 587,           // Required
    secure: false,       // Required
    auth: { user: '...', pass: '...' }
  }
};
```

### After (v1.0.3+)
```javascript
// Smart defaults are applied automatically
const emailConfig = {
  to: 'user@example.com',
  smtp: {
    host: 'smtp.gmail.com',
    // port and secure are automatically configured
    auth: { user: '...', pass: '...' }
  }
};
```

## Best Practices

1. **Test connections** before generating PDFs in production
2. **Use App Passwords** for Gmail and Yahoo instead of regular passwords
3. **Enable 2FA** and generate app-specific passwords for better security
4. **Let smart defaults** handle port/security configuration
5. **Check error messages** for specific guidance when issues occur

## Troubleshooting

### Common Issues

**Authentication Failed**
- Use App Passwords for Gmail/Yahoo
- Verify username/password are correct
- Check if 2FA is enabled

**Connection Refused**
- Verify SMTP host and port
- Check firewall settings
- Ensure the provider allows SMTP access

**Socket Close Errors**
- Usually indicates port/security mismatch
- Let smart defaults configure port and secure settings
- For Gmail: use port 587 with secure=false OR port 465 with secure=true

**Certificate Errors**
- Try setting `rejectUnauthorized: false` in SMTP config (reduces security)
- Verify the SMTP host supports SSL/TLS

### Getting Help

The enhanced error messages now provide specific guidance for common issues. If you encounter problems:

1. Check the detailed error message
2. Verify your provider's SMTP settings
3. Test the connection using `testEmailConnection()`
4. Refer to your email provider's documentation for SMTP setup

## API Reference

### New Functions

- `testEmailConnection(config)` - Test SMTP connection
- `validateSmtpConfig(config)` - Validate SMTP configuration
- `applySmartEmailDefaults(config)` - Apply provider-specific defaults

### Enhanced Functions

- `validateEmailConfig(config)` - Now includes smart defaults and auto-correction
- `generatePdf(options)` - Better error messages for email failures
