Skip to content

ashish7802/email-artisan

Repository files navigation

πŸ“§ Python Email Automation Tool

A lightweight, production-style email automation API built with FastAPI β€” supports single SMTP sends, bulk CSV campaigns, environment-based config, structured logging, and unit tests.

Python FastAPI SMTP License


✨ Features

  • πŸ“¨ Single email sending via SMTP (TLS/SSL support)
  • πŸ“‹ Bulk email campaigns from a CSV file
  • πŸ” Environment variable config β€” no secrets in code
  • πŸ“ Structured logging with log levels and file output
  • πŸ§ͺ Unit tests with pytest
  • πŸ—‚ Modular architecture β€” clean separation of concerns
  • ⚑ FastAPI with automatic OpenAPI docs at /docs

πŸ“ Project Structure

email-automation/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ api/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   └── routes/
β”‚   β”‚       β”œβ”€β”€ __init__.py
β”‚   β”‚       β”œβ”€β”€ email.py          # Single email endpoint
β”‚   β”‚       └── bulk.py           # Bulk CSV email endpoint
β”‚   β”œβ”€β”€ core/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ config.py             # Settings from .env via Pydantic
β”‚   β”‚   └── logging.py            # Logger setup
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   └── email.py              # Pydantic request/response models
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   └── email_service.py      # SMTP logic (single + bulk)
β”‚   └── utils/
β”‚       β”œβ”€β”€ __init__.py
β”‚       └── csv_parser.py         # CSV reading and validation
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ test_email_service.py     # Unit tests for email service
β”‚   └── test_csv_parser.py        # Unit tests for CSV utility
β”œβ”€β”€ sample_data/
β”‚   └── recipients.csv            # Example bulk email CSV
β”œβ”€β”€ logs/                         # Auto-created at runtime
β”œβ”€β”€ .env.example                  # Environment variable template
β”œβ”€β”€ .gitignore
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ main.py                       # App entrypoint
└── README.md

πŸš€ Getting Started

1. Clone the Repository

git clone https://github.com/yourusername/email-automation.git
cd email-automation

2. Create & Activate a Virtual Environment

python -m venv venv

# macOS / Linux
source venv/bin/activate

# Windows
venv\Scripts\activate

3. Install Dependencies

pip install -r requirements.txt

4. Configure Environment Variables

cp .env.example .env

Open .env and fill in your SMTP credentials:

# SMTP Configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=your_email@gmail.com
SMTP_PASSWORD=your_app_password
SMTP_USE_TLS=true

# Sender Info
DEFAULT_SENDER_NAME=Your Name
DEFAULT_SENDER_EMAIL=your_email@gmail.com

# App Settings
APP_ENV=development
LOG_LEVEL=INFO
LOG_FILE=logs/app.log

Gmail users: Use an App Password, not your account password.

5. Run the Server

uvicorn main:app --reload

API is now live at: http://localhost:8000
Interactive docs: http://localhost:8000/docs


πŸ“‘ API Endpoints

POST /api/email/send

Send a single email.

Request Body:

{
  "to": "recipient@example.com",
  "subject": "Hello from FastAPI",
  "body": "This is a test email.",
  "html": false
}

Response:

{
  "status": "success",
  "message": "Email sent to recipient@example.com"
}

POST /api/email/bulk

Send emails to multiple recipients from an uploaded CSV file.

Form Data:

  • file β€” CSV file upload (see format below)
  • subject β€” Email subject line
  • body β€” Email body text (supports {name} placeholder)

Example recipients.csv:

name,email
Alice Johnson,alice@example.com
Bob Smith,bob@example.com
Carol White,carol@example.com

Response:

{
  "status": "success",
  "total": 3,
  "sent": 3,
  "failed": 0,
  "errors": []
}

GET /api/email/health

Health check endpoint.

{ "status": "ok", "smtp_connected": true }

πŸ§ͺ Running Tests

pytest tests/ -v

Example output:

tests/test_email_service.py::test_build_message_plain        PASSED
tests/test_email_service.py::test_build_message_html         PASSED
tests/test_email_service.py::test_send_raises_on_bad_config  PASSED
tests/test_csv_parser.py::test_parse_valid_csv               PASSED
tests/test_csv_parser.py::test_parse_missing_email_column    PASSED
tests/test_csv_parser.py::test_parse_empty_file              PASSED

6 passed in 0.42s

πŸ“‹ Requirements

requirements.txt

fastapi==0.111.0
uvicorn[standard]==0.29.0
pydantic==2.7.0
pydantic-settings==2.2.1
python-multipart==0.0.9
python-dotenv==1.0.1
pytest==8.2.0
pytest-asyncio==0.23.6
httpx==0.27.0

βš™οΈ Core Module Reference

app/core/config.py

Uses pydantic-settings to load and validate all environment variables at startup. Raises a clear error if required variables are missing.

app/services/email_service.py

Handles all SMTP logic:

  • Opens a single connection per request (context manager)
  • Supports text/plain and text/html content types
  • Bulk sends iterate recipients with per-email error capture β€” one failure won't abort the batch

app/utils/csv_parser.py

  • Validates CSV has required email column
  • Strips whitespace from all fields
  • Returns a typed list of Recipient objects

app/core/logging.py

  • Logs to both console and logs/app.log
  • Log level controlled by LOG_LEVEL env var
  • Format: [timestamp] [LEVEL] module: message

πŸ”’ Security Notes

  • Never commit .env to version control β€” it's included in .gitignore
  • Use App Passwords or OAuth2 tokens instead of raw SMTP passwords
  • For production, consider rate-limiting the /bulk endpoint
  • Validate and sanitize all CSV inputs before sending

🌐 Deployment

Docker

docker build -t email-automation .
docker run -p 8000:8000 --env-file .env email-automation

Render / Railway / Fly.io

  1. Connect your GitHub repo
  2. Set environment variables in the platform dashboard
  3. Set start command: uvicorn main:app --host 0.0.0.0 --port 8000

🀝 Contributing

  1. Fork the repo
  2. Create a branch: git checkout -b feat/your-feature
  3. Commit: git commit -m 'feat: describe your change'
  4. Push: git push origin feat/your-feature
  5. Open a Pull Request

πŸ“„ License

MIT Β© [Ashish Yadav]


Built with ⚑ FastAPI Β· πŸ“§ SMTP Β· 🐍 Python

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors