# DirectMailer Plugin Documentation

The DirectMailer plugin provides a simplified interface for sending emails in the ION Club Yii2 application using Symfony Mailer.

## Features

- Simple text and HTML email sending
- Template-based emails with parameters
- Bulk email sending with rate limiting
- Email attachments support
- CC and BCC recipients
- Built-in debugging and logging
- Pre-configured email helpers for common scenarios
- Console commands for testing and management

## Configuration

The DirectMailer component is configured in `/common/config/main.php`:

```php
'directMailer' => [
    'class' => 'common\components\DirectMailer',
    'defaultFrom' => $params['adminEmail'] ?? 'noreply@example.com',
    'defaultFromName' => 'ION Club System',
    'defaultReplyTo' => $params['supportEmail'] ?? null,
    'debugMode' => YII_DEBUG,
    'defaultHeaders' => [
        'X-Mailer' => 'ION Club DirectMailer',
        'X-Priority' => '3',
    ],
],
```

## Basic Usage

### Send Simple Text Email

```php
$success = Yii::$app->directMailer->sendText(
    'recipient@example.com',
    'Test Subject',
    'This is the email body'
);
```

### Send HTML Email

```php
$success = Yii::$app->directMailer->sendHtml(
    'recipient@example.com',
    'HTML Subject',
    '<h1>Hello World</h1><p>This is an HTML email</p>'
);
```

### Send Email with Attachment

```php
$success = Yii::$app->directMailer->sendWithAttachment(
    'recipient@example.com',
    'Email with Attachment',
    'Please find the attached file.',
    '/path/to/file.pdf'
);
```

### Send Email Using Template

```php
$success = Yii::$app->directMailer->sendTemplate(
    'recipient@example.com',
    'Welcome!',
    'welcome-email',
    ['name' => 'John Doe', 'company' => 'ACME Corp']
);
```

### Send Email with CC and BCC

```php
$success = Yii::$app->directMailer->sendWithCopies(
    'primary@example.com',           // TO
    'Important Message',             // Subject
    'This is the message body',      // Body
    ['cc1@example.com', 'cc2@example.com'],     // CC
    ['bcc1@example.com', 'bcc2@example.com'],   // BCC
    false,                           // isHtml
    'sender@example.com',            // From (optional)
    'Custom Sender Name'             // From Name (optional)
);
```

## Bulk Email Sending

```php
$emails = [
    ['to' => 'user1@example.com', 'subject' => 'Subject 1', 'body' => 'Body 1'],
    ['to' => 'user2@example.com', 'subject' => 'Subject 2', 'body' => 'Body 2'],
    // ... more emails
];

$results = Yii::$app->directMailer->sendBulk(
    $emails,
    false,  // isHtml
    10,     // batchSize
    1       // delaySeconds between batches
);

// Check results
foreach ($results as $result) {
    if ($result['success']) {
        echo "Email sent successfully to: " . $result['to'] . "\n";
    } else {
        echo "Failed to send email to: " . $result['to'] . "\n";
    }
}
```

## Email Helper Functions

The `EmailHelper` class provides convenient methods for common email scenarios:

### Welcome Email

```php
$success = EmailHelper::sendWelcomeEmail(
    'newuser@example.com',
    'John Doe',
    'https://yoursite.com/login'
);
```

### Booking Confirmation

```php
$bookingData = [
    'bookingNumber' => 'ION20241201001',
    'customerName' => 'John Doe',
    'serviceType' => 'Windsurfing Lesson',
    'bookingDate' => '2024-12-15',
    'bookingTime' => '10:00 AM',
    'totalAmount' => '€75.00',
];

$success = EmailHelper::sendBookingConfirmation(
    'customer@example.com',
    $bookingData
);
```

### System Notification

```php
$success = EmailHelper::sendNotification(
    'user@example.com',
    'John Doe',
    'Your booking has been confirmed.',
    false  // urgent flag
);
```

### Admin Notification

```php
$success = EmailHelper::sendAdminNotification(
    'System Alert',
    'High memory usage detected on server.',
    ['usage' => '95%', 'timestamp' => date('Y-m-d H:i:s')]
);
```

### Error Notification

```php
$success = EmailHelper::sendErrorNotification(
    'Database connection failed',
    [
        'file' => __FILE__,
        'line' => __LINE__,
        'trace' => debug_backtrace()
    ]
);
```

## Available Email Templates

The following email templates are available in `/common/mail/`:

- `welcome-email.php` - Welcome email for new users
- `booking-confirmation.php` - Booking confirmation email
- `notification.php` - General system notification
- `passwordResetToken-html.php` - Password reset email (built-in)

## Console Commands

Use these console commands for testing and managing emails:

### Test Email Configuration

```bash
./yii email/test                        # Test with admin email
./yii email/test user@example.com       # Test with specific email
```

### Send Individual Emails

```bash
./yii email/send-welcome user@example.com "John Doe"
./yii email/send-notification user@example.com "John" "Test message"
./yii email/send-text user@example.com "Subject" "Message"
./yii email/send-html user@example.com "Subject" "<h1>HTML Content</h1>"
```

### Send Test Booking

```bash
./yii email/test-booking user@example.com
```

### View Configuration

```bash
./yii email/config                      # Show email configuration
./yii email/list-templates              # List available templates
```

### Send Admin Notification

```bash
./yii email/send-admin-notification "Alert" "Server memory usage high"
```

## Creating Custom Email Templates

1. Create a new PHP file in `/common/mail/` directory
2. Use the following template structure:

```php
<?php
use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $name string */
/* @var $customVar string */

$this->title = 'Your Email Title';
?>

<h2>Your Email Title</h2>

<p>Hello <?= Html::encode($name) ?>,</p>

<p>Your email content here with <?= Html::encode($customVar) ?></p>

<p>Best regards,<br>
The ION Club Team</p>
```

3. Use it in your code:

```php
$success = Yii::$app->directMailer->sendTemplate(
    'recipient@example.com',
    'Email Subject',
    'your-template-name',
    [
        'name' => 'John Doe',
        'customVar' => 'custom value'
    ]
);
```

## Error Handling and Logging

The DirectMailer automatically logs errors and can be configured to log all email activity:

```php
// Enable debug mode in configuration
'directMailer' => [
    'class' => 'common\components\DirectMailer',
    'debugMode' => true,  // Will log all email sending attempts
    // ... other config
],
```

When debug mode is enabled, all email sending attempts are logged with details about recipients, subjects, and success status.

## Security Considerations

1. **Validate Email Addresses**: Always validate email addresses before sending
2. **Sanitize Content**: Use `Html::encode()` for user-generated content in templates
3. **Rate Limiting**: Use the bulk sending features for large email campaigns
4. **Authentication**: Ensure proper authentication before allowing email sending
5. **Attachments**: Validate file types and sizes before attaching files

## Example Usage in Controllers

```php
<?php

namespace backend\controllers;

use Yii;
use yii\web\Controller;
use common\components\EmailHelper;

class NotificationController extends Controller
{
    public function actionSendWelcome()
    {
        $userEmail = 'newuser@example.com';
        $userName = 'John Doe';
        
        $success = EmailHelper::sendWelcomeEmail($userEmail, $userName);
        
        if ($success) {
            Yii::$app->session->setFlash('success', 'Welcome email sent successfully!');
        } else {
            Yii::$app->session->setFlash('error', 'Failed to send welcome email.');
        }
        
        return $this->redirect(['index']);
    }
    
    public function actionSendCustom()
    {
        $success = Yii::$app->directMailer->sendHtml(
            'customer@example.com',
            'Special Offer',
            '<h1>Special Offer!</h1><p>Get 20% off your next booking!</p>'
        );
        
        return $this->asJson(['success' => $success]);
    }
}
```

## Troubleshooting

### Common Issues

1. **Emails not sending**: Check SMTP configuration in `/common/config/main-local.php`
2. **Templates not found**: Ensure template files exist in `/common/mail/` directory
3. **Permission errors**: Check file permissions on mail directory and log files
4. **Memory issues with bulk sending**: Reduce batch size or increase memory limit

### Debug Tips

1. Enable debug mode in DirectMailer configuration
2. Check application logs for error messages
3. Use the console test commands to verify configuration
4. Test with a simple text email first before trying complex templates

## Performance Optimization

1. **Use Bulk Sending**: For multiple emails, use `sendBulk()` method
2. **Optimize Templates**: Keep email templates simple and lightweight
3. **Cache Templates**: Consider caching rendered templates for repeated use
4. **Queue Large Campaigns**: For very large email campaigns, consider using Yii2 Queue

## Integration with Yii2 Queue

For large-scale email sending, you can integrate with Yii2 Queue:

```php
// Create a job for sending emails
Yii::$app->queue->push(new \common\jobs\SendEmailJob([
    'to' => 'recipient@example.com',
    'subject' => 'Subject',
    'template' => 'template-name',
    'params' => ['name' => 'John Doe']
]));
```

This documentation covers the main features and usage patterns of the DirectMailer plugin. For additional customization or specific requirements, you can extend the DirectMailer class or create additional helper methods.
