# Mail Module Documentation

## Overview
The Mail Module provides a comprehensive email sending system with the ability to send emails to users, clients, and custom email addresses. All sent emails are logged in the database with their status and error tracking.

## Features
- Send emails to registered users
- Send emails to clients
- Send emails to custom email addresses
- Email logging and tracking
- Failed email retry mechanism
- Status tracking (pending, sent, failed)
- Email history for users and clients
- Beautiful HTML email templates

## Database Schema

### Mails Table
- `id` - Primary key
- `name` - Recipient name
- `email` - Recipient email address
- `subject` - Email subject
- `body` - Email body content
- `status` - Email status (pending, sent, failed)
- `sent_at` - Timestamp when email was sent
- `recipient_type` - Type of recipient (user, client, or null for custom)
- `recipient_id` - ID of the recipient (user_id or client_id)
- `error_message` - Error message if sending failed
- `created_at` - Record creation timestamp
- `updated_at` - Record update timestamp
- `deleted_at` - Soft delete timestamp

## API Endpoints

### 1. Contact Form Submission (Public)
**Endpoint:** `POST /api/mails`  
**Authentication:** Not Required (Public)  
**Description:** Submit a contact form. Creates mail record in database and notifies all users.

**Request Body:**
```json
{
  "name": "John Doe",
  "email": "john@example.com",
  "subject": "Question about your services",
  "body": "I would like to know more about your pricing and available packages."
}
```

**Response:**
```json
{
  "message": "Contact form submitted successfully",
  "contact_mail_id": 15,
  "users_notified": 5,
  "failed_count": 0
}
```

**What happens:**
1. A mail record is created in the database with the customer's contact information (status: pending)
2. All users in the system receive a notification email about the new contact message (emails sent directly, NOT saved in DB)
3. The customer does NOT receive a confirmation email (mail is only stored in DB for their record)

### 2. List All Mails
**Endpoint:** `GET /api/mails`  
**Authentication:** Required  
**Description:** Get a list of all sent emails

**Response:**
```json
[
  {
    "id": 1,
    "name": "John Doe",
    "email": "john@example.com",
    "subject": "Welcome",
    "body": "Welcome to our platform!",
    "status": "sent",
    "sent_at": "2025-10-08T12:00:00.000000Z",
    "recipient_type": "user",
    "recipient_id": 1,
    "error_message": null,
    "created_at": "2025-10-08T12:00:00.000000Z",
    "updated_at": "2025-10-08T12:00:00.000000Z"
  }
]
```

### 2. Get Specific Mail
**Endpoint:** `GET /api/mails/{id}`  
**Authentication:** Required  
**Description:** Get details of a specific email

**Response:**
```json
{
  "id": 1,
  "name": "John Doe",
  "email": "john@example.com",
  "subject": "Welcome",
  "body": "Welcome to our platform!",
  "status": "sent",
  "sent_at": "2025-10-08T12:00:00.000000Z",
  "recipient_type": "user",
  "recipient_id": 1,
  "error_message": null,
  "created_at": "2025-10-08T12:00:00.000000Z",
  "updated_at": "2025-10-08T12:00:00.000000Z"
}
```

### 3. Send Email to User (Protected)
**Endpoint:** `POST /api/mails/send-to-user`  
**Authentication:** Required  
**Description:** Send an email to a registered user

**Request Body:**
```json
{
  "user_id": 1,
  "subject": "Account Update",
  "body": "Your account has been updated successfully."
}
```

**Response:**
```json
{
  "message": "Email sent successfully to user",
  "mail": {
    "id": 1,
    "name": "John Doe",
    "email": "john@example.com",
    "subject": "Account Update",
    "body": "Your account has been updated successfully.",
    "status": "sent",
    "sent_at": "2025-10-08T12:00:00.000000Z",
    "recipient_type": "user",
    "recipient_id": 1,
    "error_message": null,
    "created_at": "2025-10-08T12:00:00.000000Z",
    "updated_at": "2025-10-08T12:00:00.000000Z"
  }
}
```

### 4. Send Email to Client (Protected)
**Endpoint:** `POST /api/mails/send-to-client`  
**Authentication:** Required  
**Description:** Send an email to a client (you must provide the email address)

**Request Body:**
```json
{
  "client_id": 1,
  "email": "info@acme.com",
  "subject": "Project Update",
  "body": "Your project has been completed successfully."
}
```

**Response:**
```json
{
  "message": "Email sent successfully to client",
  "mail": {
    "id": 2,
    "name": "Acme Corp",
    "email": "info@acme.com",
    "subject": "Project Update",
    "body": "Your project has been completed successfully.",
    "status": "sent",
    "sent_at": "2025-10-08T12:00:00.000000Z",
    "recipient_type": "client",
    "recipient_id": 1,
    "error_message": null,
    "created_at": "2025-10-08T12:00:00.000000Z",
    "updated_at": "2025-10-08T12:00:00.000000Z"
  }
}
```

**Note:** The client_id is used to link the mail record to the client and retrieve the client's name. You must provide the email address where you want to send the email.

### 5. Send Email to Custom Address (Protected)
**Endpoint:** `POST /api/mails/send-to-email`  
**Authentication:** Required  
**Description:** Send an email to any email address

**Request Body:**
```json
{
  "name": "Jane Smith",
  "email": "jane@example.com",
  "subject": "Notification",
  "body": "This is a custom notification email."
}
```

**Response:**
```json
{
  "message": "Email sent successfully",
  "mail": {
    "id": 3,
    "name": "Jane Smith",
    "email": "jane@example.com",
    "subject": "Notification",
    "body": "This is a custom notification email.",
    "status": "sent",
    "sent_at": "2025-10-08T12:00:00.000000Z",
    "recipient_type": null,
    "recipient_id": null,
    "error_message": null,
    "created_at": "2025-10-08T12:00:00.000000Z",
    "updated_at": "2025-10-08T12:00:00.000000Z"
  }
}
```

### 6. Resend Failed Email
**Endpoint:** `POST /api/mails/{id}/resend`  
**Authentication:** Required  
**Description:** Retry sending a failed email

**Response:**
```json
{
  "message": "Email resent successfully",
  "mail": {
    "id": 1,
    "name": "John Doe",
    "email": "john@example.com",
    "subject": "Welcome",
    "body": "Welcome to our platform!",
    "status": "sent",
    "sent_at": "2025-10-08T12:05:00.000000Z",
    "recipient_type": "user",
    "recipient_id": 1,
    "error_message": null,
    "created_at": "2025-10-08T12:00:00.000000Z",
    "updated_at": "2025-10-08T12:05:00.000000Z"
  }
}
```

### 7. Get Mails by Status
**Endpoint:** `GET /api/mails/status/{status}`  
**Authentication:** Required  
**Description:** Get all emails with a specific status (pending, sent, failed)

**Example:** `GET /api/mails/status/failed`

**Response:**
```json
[
  {
    "id": 4,
    "name": "Test User",
    "email": "test@example.com",
    "subject": "Test",
    "body": "Test email",
    "status": "failed",
    "sent_at": null,
    "recipient_type": "user",
    "recipient_id": 5,
    "error_message": "SMTP connection failed",
    "created_at": "2025-10-08T12:00:00.000000Z",
    "updated_at": "2025-10-08T12:00:00.000000Z"
  }
]
```

### 8. Get User's Mail History
**Endpoint:** `GET /api/mails/user/{userId}`  
**Authentication:** Required  
**Description:** Get all emails sent to a specific user

**Response:**
```json
[
  {
    "id": 1,
    "name": "John Doe",
    "email": "john@example.com",
    "subject": "Welcome",
    "body": "Welcome to our platform!",
    "status": "sent",
    "sent_at": "2025-10-08T12:00:00.000000Z",
    "recipient_type": "user",
    "recipient_id": 1,
    "error_message": null,
    "created_at": "2025-10-08T12:00:00.000000Z",
    "updated_at": "2025-10-08T12:00:00.000000Z"
  }
]
```

### 9. Get Client's Mail History
**Endpoint:** `GET /api/mails/client/{clientId}`  
**Authentication:** Required  
**Description:** Get all emails sent to a specific client

**Response:**
```json
[
  {
    "id": 2,
    "name": "Acme Corp",
    "email": "info@acme.com",
    "subject": "Project Update",
    "body": "Your project has been completed successfully.",
    "status": "sent",
    "sent_at": "2025-10-08T12:00:00.000000Z",
    "recipient_type": "client",
    "recipient_id": 1,
    "error_message": null,
    "created_at": "2025-10-08T12:00:00.000000Z",
    "updated_at": "2025-10-08T12:00:00.000000Z"
  }
]
```

### 10. Delete Mail
**Endpoint:** `DELETE /api/mails/{id}`  
**Authentication:** Required  
**Description:** Soft delete a mail record

**Response:**
```json
{
  "message": "Mail deleted successfully"
}
```

## Email Configuration

### Environment Variables
Add these to your `.env` file:

```env
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@yourdomain.com
MAIL_FROM_NAME="${APP_NAME}"
```

### Popular Email Services

#### Gmail
```env
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your_app_password
MAIL_ENCRYPTION=tls
```

#### SendGrid
```env
MAIL_MAILER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=apikey
MAIL_PASSWORD=your_sendgrid_api_key
MAIL_ENCRYPTION=tls
```

#### Mailgun
```env
MAIL_MAILER=mailgun
MAILGUN_DOMAIN=your_domain.mailgun.org
MAILGUN_SECRET=your_mailgun_api_key
```

#### For Development (Log emails to file)
```env
MAIL_MAILER=log
MAIL_LOG_CHANNEL=stack
```

## Usage Examples

### Using cURL

#### Submit Contact Form (No Authentication Required)
```bash
curl -X POST http://localhost:8000/api/mails \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Jane Smith",
    "email": "jane@example.com",
    "subject": "Inquiry about your services",
    "body": "I am interested in learning more about your offerings. Could you please provide more information?"
  }'
```

#### Send Email to User
```bash
curl -X POST http://localhost:8000/api/mails/send-to-user \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": 1,
    "subject": "Welcome to our platform",
    "body": "Thank you for joining us!"
  }'
```

#### Send Email to Client
```bash
curl -X POST http://localhost:8000/api/mails/send-to-client \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": 1,
    "email": "info@acme.com",
    "subject": "Project Status Update",
    "body": "Your project is now complete."
  }'
```

#### Send Email to Custom Address
```bash
curl -X POST http://localhost:8000/api/mails/send-to-email \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com",
    "subject": "Custom Notification",
    "body": "This is a custom message."
  }'
```

#### Get Failed Emails
```bash
curl -X GET http://localhost:8000/api/mails/status/failed \
  -H "Authorization: Bearer YOUR_TOKEN"
```

#### Resend Failed Email
```bash
curl -X POST http://localhost:8000/api/mails/1/resend \
  -H "Authorization: Bearer YOUR_TOKEN"
```

## Email Template

The module uses a beautiful HTML email template located at `resources/views/emails/generic.blade.php`. The template includes:

- Professional header with app name
- Personalized greeting
- Clean content area
- Professional footer
- Responsive design
- Modern styling

## Error Handling

The module handles various email sending errors:

- **SMTP Connection Failures**: Logged with error message
- **Invalid Email Addresses**: Validated before sending
- **Missing Client Email**: Returns descriptive error
- **Network Issues**: Captured and logged

All errors are stored in the `error_message` field of the mail record.

## Status Types

- **pending**: Email is queued but not sent yet
- **sent**: Email was successfully sent
- **failed**: Email sending failed (check error_message)

## Integration with Clients

The module integrates with the Clients module. To send emails related to clients:

1. Use the `send-to-client` endpoint with the client's ID and the recipient's email address
2. The client's name will be automatically used in the email
3. The mail record will be linked to the client for tracking purposes

**Important:** Clients do not store email addresses. You must provide the email address each time you send an email to/about a client. This allows flexibility to send emails to different contacts for the same client.

## Best Practices

1. **Development**: Use `MAIL_MAILER=log` to log emails to file instead of sending
2. **Testing**: Use Mailtrap or similar services to test email sending
3. **Production**: Use reliable SMTP services like SendGrid, Mailgun, or AWS SES
4. **Queue**: Consider using Laravel queues for sending bulk emails
5. **Error Monitoring**: Regularly check failed emails and retry them
6. **Email Validation**: Always validate email addresses before sending
7. **Rate Limiting**: Be aware of your email service's rate limits

## Troubleshooting

### Emails Not Sending
- Check your `.env` configuration
- Verify SMTP credentials
- Check firewall/network settings
- Review failed emails for error messages

### Testing Email Configuration
Use this command to test your email configuration:
```bash
php artisan tinker
Mail::raw('Test email', function($msg) {
    $msg->to('test@example.com')->subject('Test');
});
```

## Files Structure

```
app/
├── Http/
│   └── Controllers/
│       └── MailController.php      # API endpoints
├── Mail/
│   └── GenericMail.php             # Mailable class
├── Models/
│   └── Mail.php                    # Mail model
└── Services/
    └── MailService.php             # Business logic

resources/
└── views/
    └── emails/
        └── generic.blade.php       # Email template

routes/
└── mails.php                       # Mail routes

database/
└── migrations/
    ├── *_create_mails_table.php
    └── *_add_additional_fields_to_mails_table.php
```

## Future Enhancements

- Queue support for bulk emails
- Email templates management
- Email scheduling
- Attachments support
- CC/BCC support
- HTML vs Plain text option
- Email analytics
- Bounce handling
- Unsubscribe management
