# 📧 Gmail Clone - Full Email Platform

A complete, production-ready email platform built with PHP and MySQL, featuring a modern Gmail-like interface.

![PHP Version](https://img.shields.io/badge/PHP-7.4+-blue.svg)
![MySQL Version](https://img.shields.io/badge/MySQL-5.7+-orange.svg)
![License](https://img.shields.io/badge/License-MIT-green.svg)

## 🚀 Features

### ✅ Core Features
- **User Authentication** - Secure registration and login with password hashing
- **Compose & Send Emails** - Rich text editor with file attachments
- **Inbox Management** - View, star, and organize emails
- **Sent Emails** - Track all sent messages
- **Trash & Restore** - Soft delete with restore functionality
- **Starred Emails** - Mark important messages
- **Search Functionality** - Full-text search across all emails
- **Pagination** - Efficient email browsing

### 🎨 UI/UX Features
- **Gmail-like Interface** - Modern, responsive design
- **Real-time Updates** - AJAX-powered interactions
- **Keyboard Shortcuts** - Ctrl+Enter to send, Ctrl+S to save draft
- **Mobile Responsive** - Works on all devices
- **Avatar System** - Color-coded user avatars
- **Unread Indicators** - Visual distinction for unread emails

### 🔐 Security Features
- **Prepared Statements** - SQL injection prevention
- **CSRF Protection** - Cross-site request forgery prevention
- **Password Hashing** - Bcrypt encryption
- **Session Management** - Secure session handling
- **Input Validation** - XSS prevention
- **Remember Me** - Secure token-based authentication

## 📋 Requirements

- PHP 7.4 or higher
- MySQL 5.7 or higher
- Apache/Nginx web server
- Composer (for PHPMailer)

## 🛠️ Installation

### 1. Clone the Repository
```bash
git clone https://github.com/yourusername/gmail-clone.git
cd gmail-clone
```

### 2. Database Setup
```bash
# Import the database schema
mysql -u root -p < database.sql
```

### 3. Configure Database
Edit `config/database.php` and update your database credentials:
```php
define('DB_HOST', 'localhost');
define('DB_USER', 'your_username');
define('DB_PASS', 'your_password');
define('DB_NAME', 'email_system');
```

### 4. Install Dependencies
```bash
composer require phpmailer/phpmailer
```

### 5. Set Up Web Server
Point your web server's document root to the project directory.

For Apache, ensure `mod_rewrite` is enabled.

### 6. Access the Application
Open your browser and navigate to:
```
http://localhost/webmail/
```

## 📁 Project Structure

```
gmail-clone/
├── api/                    # API endpoints
│   ├── toggle_star.php
│   ├── toggle_read.php
│   ├── delete_email.php
│   ├── archive_email.php
│   ├── bulk_delete.php
│   ├── bulk_mark_read.php
│   ├── restore_email.php
│   ├── delete_forever.php
│   ├── bulk_restore.php
│   ├── bulk_delete_forever.php
│   └── empty_trash.php
├── config/
│   └── database.php        # Database configuration
├── uploads/
│   └── attachments/        # Email attachments
├── compose.php             # Compose email page
├── inbox.php               # Inbox view
├── sent.php                # Sent emails view
├── starred.php             # Starred emails view
├── trash.php               # Trash view
├── view.php                # View single email
├── register.php            # User registration
├── login.php               # User login
├── logout.php              # User logout
├── database.sql            # Database schema
├── composer.json           # PHP dependencies
└── README.md               # This file
```

## 🗄️ Database Schema

### Users Table
```sql
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(100) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    profile_picture VARCHAR(255) DEFAULT 'default.png',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
```

### Emails Table
```sql
CREATE TABLE emails (
    id INT AUTO_INCREMENT PRIMARY KEY,
    sender_id INT NOT NULL,
    receiver_id INT NOT NULL,
    subject VARCHAR(255) DEFAULT '(no subject)',
    message TEXT,
    status ENUM('sent', 'inbox', 'trash', 'draft', 'spam') DEFAULT 'inbox',
    is_read BOOLEAN DEFAULT FALSE,
    is_starred BOOLEAN DEFAULT FALSE,
    has_attachments BOOLEAN DEFAULT FALSE,
    thread_id INT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (sender_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (receiver_id) REFERENCES users(id) ON DELETE CASCADE
);
```

### Attachments Table
```sql
CREATE TABLE attachments (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email_id INT NOT NULL,
    file_name VARCHAR(255) NOT NULL,
    file_path VARCHAR(255) NOT NULL,
    file_size INT,
    file_type VARCHAR(100),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (email_id) REFERENCES emails(id) ON DELETE CASCADE
);
```

## 🔧 Configuration

### Email Settings (PHPMailer)
Edit `config/database.php` to configure SMTP settings:
```php
define('SMTP_HOST', 'smtp.gmail.com');
define('SMTP_PORT', 587);
define('SMTP_USERNAME', 'your@gmail.com');
define('SMTP_PASSWORD', 'your-app-password');
define('SMTP_ENCRYPTION', 'tls');
```

### Pagination
Adjust emails per page:
```php
define('EMAILS_PER_PAGE', 20);
```

### Session Lifetime
Configure session timeout (in seconds):
```php
define('SESSION_LIFETIME', 3600); // 1 hour
```

## 🎯 Usage

### Demo Accounts
The system comes with pre-configured demo accounts:
- **Email:** john@example.com | **Password:** password123
- **Email:** jane@example.com | **Password:** password123
- **Email:** demo@example.com | **Password:** password123

### Keyboard Shortcuts
- **Ctrl/Cmd + Enter** - Send email
- **Ctrl/Cmd + S** - Save as draft

### Email Actions
- **Star** - Click the star icon to mark important
- **Archive** - Remove from inbox without deleting
- **Delete** - Move to trash
- **Restore** - Recover from trash
- **Delete Forever** - Permanently delete

## 🔒 Security Best Practices

1. **Use HTTPS** - Always serve over SSL/TLS
2. **Strong Passwords** - Enforce password complexity
3. **Regular Updates** - Keep PHP and dependencies updated
4. **Backup Database** - Regular backups recommended
5. **Rate Limiting** - Implement login attempt limits
6. **Input Sanitization** - All inputs are sanitized
7. **CSRF Tokens** - All forms include CSRF protection

## 🚀 Advanced Features (To Implement)

### Planned Features
- [ ] Email threading (conversations)
- [ ] Labels and folders
- [ ] Email filters and rules
- [ ] Auto-reply functionality
- [ ] Email templates
- [ ] Contact management
- [ ] Calendar integration
- [ ] Two-factor authentication
- [ ] Email encryption (PGP)
- [ ] Spam filtering
- [ ] Real-time notifications (WebSocket)
- [ ] Mobile app (React Native)

### Integration Options
- **PHPMailer** - For SMTP email sending
- **Mailgun** - Transactional email service
- **SendGrid** - Email delivery platform
- **Postfix** - Self-hosted mail server
- **Dovecot** - IMAP/POP3 server

## 🐛 Troubleshooting

### Common Issues

**Database Connection Error**
```
Solution: Check database credentials in config/database.php
```

**Emails Not Sending**
```
Solution: Verify SMTP settings and enable "Less secure app access" for Gmail
```

**Session Issues**
```
Solution: Ensure session.save_path is writable in php.ini
```

**File Upload Errors**
```
Solution: Check upload_max_filesize and post_max_size in php.ini
```

## 📝 API Documentation

### Toggle Star
```http
POST /api/toggle_star.php
Content-Type: application/json

{
    "email_id": 123
}
```

### Toggle Read Status
```http
POST /api/toggle_read.php
Content-Type: application/json

{
    "email_id": 123
}
```

### Delete Email
```http
POST /api/delete_email.php
Content-Type: application/json

{
    "email_id": 123
}
```

### Bulk Operations
```http
POST /api/bulk_delete.php
Content-Type: application/json

{
    "email_ids": [123, 456, 789]
}
```

## 🤝 Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 👨‍💻 Author

**Your Name**
- GitHub: [@yourusername](https://github.com/yourusername)
- Email: your@email.com

## 🙏 Acknowledgments

- [Bootstrap](https://getbootstrap.com/) - CSS framework
- [Font Awesome](https://fontawesome.com/) - Icons
- [PHPMailer](https://github.com/PHPMailer/PHPMailer) - Email library
- [Summernote](https://summernote.org/) - Rich text editor

## 📊 Project Status

✅ **Production Ready** - All core features implemented and tested

---

**⭐ Star this repository if you found it helpful!**
