Auto-Email-Sender

Production-grade Python email automation system with CLI and Web interfaces

Stars
9
Language
Python
Updated

Auto Email Sender

A production-grade, high-end Python email automation system with advanced features including SMTP support, HTML templating, batch processing, scheduling, and comprehensive logging.

๐Ÿš€ Features

  • Modular Python Architecture - Clean, maintainable code using classes and helper functions
  • SMTP Support - Secure email sending with TLS/SSL support
  • CSV Batch Processing - Send personalized emails to multiple recipients from CSV files
  • HTML Templating - Jinja2-powered templates with variable substitution
  • Attachment Support - Send PDFs, images, and other file types
  • Scheduled Sending - Schedule emails for immediate, delayed, or recurring delivery
  • Comprehensive Logging - Track email status in SQLite database and CSV exports
  • Rich CLI Interface - Beautiful command-line interface with progress bars and tables
  • Web Interface - Optional Flask-based web dashboard (coming soon)
  • Email Validation - Built-in email address validation
  • Retry Logic - Automatic retry with exponential backoff
  • Statistics & Analytics - Detailed email sending statistics

๐Ÿ“‹ Requirements

  • Python 3.11+
  • SMTP server credentials (Gmail, Outlook, custom SMTP, etc.)

๐Ÿ› ๏ธ Installation

  1. Clone the repository:

    git clone <repository-url>
    cd Auto-Email-Sender
    
  2. Create a virtual environment:

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
    
  3. Install dependencies:

    pip install -r requirements.txt
    
  4. Configure environment variables:

    cp env.example .env
    # Edit .env with your SMTP credentials
    

โš™๏ธ Configuration

Create a .env file with your SMTP settings:

# SMTP Configuration
SMTP_SERVER=smtp.gmail.com
SMTP_PORT=587
[email protected]
SMTP_PASSWORD=your_app_password
SMTP_USE_TLS=true

# Application Settings
LOG_LEVEL=INFO
MAX_RETRIES=3
BATCH_SIZE=50
[email protected]

Gmail Setup

For Gmail, you'll need to:

  1. Enable 2-factor authentication
  2. Generate an App Password
  3. Use the App Password in your .env file

๐Ÿ“– Usage

Command Line Interface

The application provides a rich CLI with multiple commands:

1. Send Emails Immediately
# Interactive mode
python -m src.main send

# With command line options
python -m src.main send \
  --csv-file data/recipients.csv \
  --subject "Welcome to Our Service" \
  --template templates/sample_template.html \
  --attachments document.pdf image.jpg
2. Schedule Emails
# Schedule for specific time
python -m src.main schedule \
  --csv-file data/recipients.csv \
  --subject "Scheduled Newsletter" \
  --template templates/sample_template.html \
  --time "2024-01-15 09:00:00"

# Schedule recurring (every Monday at 9 AM)
python -m src.main schedule \
  --csv-file data/recipients.csv \
  --subject "Weekly Newsletter" \
  --template templates/sample_template.html \
  --cron "0 9 * * 1"

# Schedule interval (every 2 hours)
python -m src.main schedule \
  --csv-file data/recipients.csv \
  --subject "Periodic Update" \
  --template templates/sample_template.html \
  --interval 120
3. Manage Scheduled Jobs
# List all scheduled jobs
python -m src.main jobs

# Cancel a job
python -m src.main cancel job_id_here
4. View Logs and Statistics
# View recent email logs
python -m src.main logs

# Show statistics
python -m src.main stats

# Export logs to CSV
python -m src.main export --output email_logs.csv
5. Test Configuration
# Test SMTP connection
python -m src.main test

CSV File Format

Your CSV file should have at least an email column, plus any additional columns for template variables:

email,name,company_name,custom_message
[email protected],John Doe,TechCorp,Welcome John!
[email protected],Jane Smith,DataFlow,Hello Jane!

HTML Templates

Templates use Jinja2 syntax with variables in double curly braces:

<!DOCTYPE html>
<html>
<body>
    <h1>Hello {{ name }}!</h1>
    <p>Welcome to {{ company_name }}.</p>
    <p>Today is {{ date }}.</p>
    <p>{{ custom_message }}</p>
</body>
</html>

Available built-in variables:

  • {{ date }} - Current date (YYYY-MM-DD)
  • {{ time }} - Current time (HH:MM:SS)
  • {{ datetime }} - Current date and time
  • {{ email }} - Recipient's email address

๐Ÿ—๏ธ Project Structure

auto-email-sender/
โ”œโ”€โ”€ src/                    # Source code
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ main.py            # CLI interface
โ”‚   โ”œโ”€โ”€ email_sender.py    # Core email functionality
โ”‚   โ”œโ”€โ”€ scheduler.py       # Email scheduling
โ”‚   โ”œโ”€โ”€ logger.py          # Logging and database
โ”‚   โ”œโ”€โ”€ utils.py           # Utility functions
โ”‚   โ””โ”€โ”€ config.py          # Configuration management
โ”œโ”€โ”€ templates/             # HTML email templates
โ”‚   โ””โ”€โ”€ sample_template.html
โ”œโ”€โ”€ data/                  # CSV files and data
โ”‚   โ””โ”€โ”€ recipients.csv
โ”œโ”€โ”€ logs/                  # Generated logs and databases
โ”œโ”€โ”€ requirements.txt       # Python dependencies
โ”œโ”€โ”€ env.example           # Environment variables template
โ””โ”€โ”€ README.md             # This file

๐Ÿ”ง Advanced Features

Custom SMTP Servers

Support for any SMTP server:

SMTP_SERVER=mail.yourcompany.com
SMTP_PORT=587
SMTP_USERNAME=your_username
SMTP_PASSWORD=your_password
SMTP_USE_TLS=true

Batch Processing

The system processes emails in batches to avoid overwhelming SMTP servers:

BATCH_SIZE=50  # Process 50 emails at a time

Retry Logic

Automatic retry with exponential backoff:

MAX_RETRIES=3  # Retry failed emails up to 3 times

Logging Levels

Configure logging verbosity:

LOG_LEVEL=INFO  # DEBUG, INFO, WARNING, ERROR

๐Ÿ“Š Monitoring and Analytics

Email Statistics

View comprehensive statistics:

python -m src.main stats

Output includes:

  • Total emails sent
  • Success/failure rates
  • Pending emails
  • Success percentage

Email Logs

Track every email sent:

python -m src.main logs

Logs include:

  • Timestamp
  • Recipient
  • Subject
  • Status (success/failed/pending)
  • Error messages
  • Template used
  • Attachments

Export Data

Export logs to CSV for external analysis:

python -m src.main export --output my_logs.csv

๐Ÿšจ Error Handling

The system includes comprehensive error handling:

  • SMTP Connection Errors - Automatic retry with exponential backoff
  • Invalid Email Addresses - Validation and logging
  • Template Errors - Detailed error messages
  • Attachment Issues - File validation and size limits
  • CSV Format Errors - Column validation and data type checking

๐Ÿ”’ Security Features

  • Environment Variables - Secure credential storage
  • TLS/SSL Support - Encrypted email transmission
  • Input Validation - Email address and file validation
  • File Size Limits - Attachment size restrictions
  • SQL Injection Protection - Parameterized database queries

๐Ÿงช Testing

Test SMTP Connection

python -m src.main test

Dry Run Mode

Test email sending without actually sending:

python -m src.main send --dry-run

๐Ÿ“ Development

Code Style

The project follows PEP 8 standards and uses:

  • Type hints throughout
  • Comprehensive docstrings
  • Modular architecture
  • Error handling best practices

Adding New Features

  1. Create feature branch
  2. Implement functionality
  3. Add tests
  4. Update documentation
  5. Submit pull request

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Update documentation
  6. Submit a pull request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ†˜ Troubleshooting

Common Issues

  1. SMTP Authentication Failed

    • Check username/password
    • Enable 2FA and use App Password for Gmail
    • Verify SMTP server settings
  2. Template Variables Not Found

    • Ensure CSV columns match template variables
    • Check for typos in variable names
    • Use {{ variable|default('fallback') }} for optional variables
  3. Attachments Not Sending

    • Check file paths are correct
    • Verify file size (max 10MB)
    • Ensure files are readable
  4. Scheduled Jobs Not Running

    • Check system timezone settings
    • Verify cron expression format
    • Check scheduler is running

Getting Help

  • Check the logs in the logs/ directory
  • Use python -m src.main test to verify configuration
  • Review error messages in the CLI output

๐ŸŽฏ Roadmap

  • Web interface with Flask
  • Email read receipts
  • Markdown to HTML conversion
  • Advanced analytics dashboard
  • API endpoints for integration
  • Multi-tenant support
  • Email campaign management
  • A/B testing capabilities

Built with โค๏ธ using Python, Jinja2, APScheduler, and Rich CLI