Metadata-Version: 2.5
Name: mail-cadence
Version: 0.3.0
Summary: Asynchronous SQLite-backed bulk email dispatch and reporting engine with XML import/export support
Project-URL: Homepage, https://github.com/krj29b/mail-cadence
Project-URL: Repository, https://github.com/krj29b/mail-cadence
Project-URL: Issues, https://github.com/krj29b/mail-cadence/issues
Author: krj29b
License: MIT License
        
        Copyright (c) 2026 Bulk Mailer Contributors
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: aiosmtplib,email,fastapi,htmx,rate-limiter,scheduler,smtp,sqlite,xml
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Environment :: Web Environment
Classifier: Framework :: AsyncIO
Classifier: Framework :: FastAPI
Classifier: Framework :: Pydantic :: 2
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Communications :: Email
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: aiosmtplib>=3.0.1
Requires-Dist: defusedxml>=0.7.1
Requires-Dist: fastapi>=0.115.0
Requires-Dist: jinja2>=3.1.4
Requires-Dist: lxml>=5.2.2
Requires-Dist: pydantic-settings>=2.4.0
Requires-Dist: pydantic-xml[lxml]>=2.11.0
Requires-Dist: pydantic>=2.8.0
Requires-Dist: python-multipart>=0.0.9
Requires-Dist: typer>=0.12.3
Requires-Dist: tzdata>=2024.1; sys_platform == 'win32'
Requires-Dist: uvicorn>=0.30.0
Provides-Extra: dev
Requires-Dist: httpx>=0.27.0; extra == 'dev'
Requires-Dist: mypy>=1.11.0; extra == 'dev'
Requires-Dist: pip-audit>=2.7.3; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23.8; extra == 'dev'
Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
Requires-Dist: pytest>=8.3.0; extra == 'dev'
Requires-Dist: radon>=6.0.1; extra == 'dev'
Requires-Dist: ruff>=0.5.5; extra == 'dev'
Requires-Dist: vulture>=2.11; extra == 'dev'
Description-Content-Type: text/markdown

# MailCadence Engine

Production-grade, asynchronous bulk email dispatch and reporting engine built in **Python 3.12+**.

## Overview

`mail-cadence` is a high-performance email dispatch engine that utilizes SQLite as its primary database backend for runtime configurations and execution history logging, while retaining full XML support for importing and exporting configuration definitions (`tasks.xml` and `schedules.xml`). It evaluates active schedule windows across timezones, dispatches scheduled email tasks concurrently with rate limiting and exponential backoff retry resilience, and sends a final Task Completion Status Report email upon completion.

---

## Key Features

- **Python 3.12+ Standards:** Built with strict type safety, `asyncio.TaskGroup`, `StrEnum`, `pydantic v2`, and `pydantic-xml`.
- **SQLite State Persistence:** SQLite runtime database storing tasks, schedules, report settings, and detailed execution logs with Write-Ahead Logging (`WAL`) mode and busy timeout handling (`30,000 ms`).
- **Safe XML Import & Export:** Built-in `defusedxml` protection against XXE and entity expansion attacks, supporting bidirectional conversion between XML documents and SQLite data models.
- **Timezone-Aware Throttling & Idempotency:** Hourly schedule windows with `zoneinfo` time zone awareness, midnight-spanning time calculation, window-level idempotency protection (`last_status == SUCCESS`), and token bucket rate limiting.
- **Async SMTP Dispatch & Retries:** High-concurrency SMTP dispatch with `aiosmtplib`, `asyncio.Semaphore`, connection pooling, exponential backoff retries on transient errors, and `--dry-run` simulation mode.
- **Jinja2 Templating:** Templated task emails with path traversal defense and auto-escaped context variables, alongside consolidated HTML/plain-text batch summary reports.

---

## Prerequisites & Installation

### Requirements
- **Python >= 3.12**
- **pip** package manager

### Installation Instructions

Clone the repository and install `mail-cadence` along with its development dependencies:

```bash
# Install in editable mode with development dependencies
python3 -m pip install -e ".[dev]"
```

Or use the provided `Makefile`:

```bash
make install
```

---

## Configuration Reference

`mail-cadence` is configured through environment variables (or a `.env` file) for SMTP server options and database location, alongside XML or database settings.

### Environment Variables (`Settings`)

Supported environment settings defined in `mail_cadence.models.Settings`:

| Variable | Default | Description |
| --- | --- | --- |
| `SMTP_HOST` | `localhost` | Hostname or IP address of the SMTP server |
| `SMTP_PORT` | `1025` | Port number for the SMTP server |
| `SMTP_USER` | *None* | Username for SMTP authentication (optional) |
| `SMTP_PASSWORD` | *None* | Password for SMTP authentication (optional) |
| `SMTP_USE_TLS` | `false` | Enable direct TLS connection (`true`/`false`) |
| `SMTP_START_TLS` | `false` | Enable STARTTLS command upgrade (`true`/`false`) |
| `SMTP_TIMEOUT` | `30.0` | Timeout in seconds for SMTP operations |
| `MAIL_CADENCE_DB` | `mail_cadence.db` | Path to SQLite database file |

---

## CLI Usage Guide (`mail-cadence`)

The package provides the `mail-cadence` CLI executable (as well as `python -m mail_cadence.cli`).

### 1. Main Dispatch Command

Executes the main bulk mailer dispatch pipeline.

```bash
mail-cadence [OPTIONS]
```

#### Flags & Options
| Option | Short | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `--tasks-xml` | `-t` | `PATH` | *None* | Optional path to tasks XML file to seed/upsert database |
| `--schedule-xml` | `-s` | `PATH` | *None* | Optional path to schedule XML file to seed/upsert database |
| `--db` | `-b` | `PATH` | `mail_cadence.db` | Path to SQLite database file (overrides `MAIL_CADENCE_DB`) |
| `--dry-run` | `-d` | `FLAG` | `false` | Execute workflow in simulation mode without sending network SMTP requests |
| `--verbose` | `-v` | `FLAG` | `false` | Enable verbose debug logging output |

#### Exit Codes
- **`0`**: Successful execution or no tasks were eligible for processing.
- **`1`**: Configuration or database error encountered (e.g. invalid file format, database connection failure).
- **`2`**: One or more tasks failed execution during the dispatch batch.

#### Example Dispatch Commands
```bash
# Execute dispatch and seed XML configurations if database is empty or needs updates
mail-cadence --tasks-xml config/samples/tasks.xml --schedule-xml config/samples/schedules.xml

# Run dispatch in dry-run mode using an existing SQLite database
mail-cadence --db mail_cadence.db --dry-run --verbose
```

---

### 2. XML Import Command (`import-xml`)

Imports task definitions and schedule rules from XML configuration files into the SQLite database.

```bash
mail-cadence import-xml [OPTIONS]
```

#### Options
| Option | Short | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `--tasks-xml` | `-t` | `PATH` | *None* | Path to tasks configuration XML file |
| `--schedule-xml` | `-s` | `PATH` | *None* | Path to schedule configuration XML file |
| `--db` | `-b` | `PATH` | `mail_cadence.db` | Target SQLite database file path |
| `--mode` | `-m` | `CHOICE` | `upsert` | Import mode: `upsert` (update/insert) or `replace` (clear and reload) |

#### Example
```bash
mail-cadence import-xml --tasks-xml config/samples/tasks.xml --schedule-xml config/samples/schedules.xml --mode upsert
```

---

### 3. XML Export Command (`export-xml`)

Exports current task definitions, schedules, and report settings from the SQLite database back into XML files.

```bash
mail-cadence export-xml [OPTIONS]
```

#### Options
| Option | Short | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `--tasks-xml` | `-t` | `PATH` | *None* | Destination path for exported tasks XML |
| `--schedule-xml` | `-s` | `PATH` | *None* | Destination path for exported schedules XML |
| `--db` | `-b` | `PATH` | `mail_cadence.db` | Source SQLite database file path |

#### Example
```bash
mail-cadence export-xml --tasks-xml exported_tasks.xml --schedule-xml exported_schedules.xml
```

---

## Development & Quality Gates

The project maintains strict code quality standards enforced via `Makefile` commands:

```bash
# Run unit and integration test suite with coverage
make test

# Run code style and linting checks (Ruff & Mypy)
make lint

# Run dead code detection (Vulture)
make dead-code

# Run code complexity analysis (Radon)
make complexity

# Run dependency vulnerability audit (pip-audit)
make audit

# Run all quality gate checks in sequence
make quality-gate
```

---

## Architectural Deep Dive

For detailed technical specifications, database entity-relationship diagrams (ERD), scheduling algorithms, Mermaid state/sequence diagrams, and security mechanics, see [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
