Metadata-Version: 2.4
Name: sendgrid-mailkit
Version: 0.1.0
Summary: SendGrid Mail Send API client with Jinja2 templates. Authenticate with SENDGRID_API_KEY — no SMTP username or password.
Author-email: Abhay Kumar Gupta <abhay.kumar@firecompass.com>
Maintainer-email: Abhay Kumar Gupta <abhay.kumar@firecompass.com>
License-Expression: MIT
Project-URL: Homepage, https://pypi.org/project/sendgrid-mailkit/
Keywords: email,sendgrid,api,templates,jinja2,mailer,sdk,transactional-email
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Communications :: Email
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Jinja2<4.0.0,>=3.1.0
Requires-Dist: python-dotenv<2.0.0,>=1.0.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-mock>=3.12.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: twine>=5.0.0; extra == "dev"
Dynamic: license-file

# sendgrid-mailkit

[![PyPI version](https://img.shields.io/pypi/v/sendgrid-mailkit.svg)](https://pypi.org/project/sendgrid-mailkit/)
[![Python Versions](https://img.shields.io/pypi/pyversions/sendgrid-mailkit.svg)](https://pypi.org/project/sendgrid-mailkit/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![Type Checked: typed](https://img.shields.io/badge/typing-typed-blue.svg)](https://www.python.org/dev/peps/pep-0561/)

A production-ready Python SDK for sending transactional and marketing emails through the **SendGrid Mail Send API**. Includes Jinja2 templating, structured logging, secure API-key handling, and a typed exception hierarchy.

---

## Features

- **SendGrid API delivery** — posts to `https://api.sendgrid.com/v3/mail/send` using your API key
- **Built-in and custom Jinja2 templates** — `welcome`, `reset_password`, `verify_account`, `getting_started`, plus your own template directory
- **Library-safe logging** — PEP 282 `NullHandler` by default; the API key is never written to logs
- **Typed exceptions** — configuration, validation, templates, authentication, timeouts, and delivery errors
- **Flexible configuration** — `.env`, environment variables, or `EmailConfig`
- **PEP 561 typed** — ships `py.typed` for MyPy and editor autocomplete

---

## Installation

```bash
pip install sendgrid-mailkit
```

Requires Python 3.9 or newer.

---

## Quick Start

### 1. Environment configuration

SMTP username and password are **not used**. Auth is a SendGrid API key only.

Create a `.env` file in **your app** (or export env vars):

```ini
SENDGRID_API_KEY=SG.your-sendgrid-api-key
EMAIL_FROM=notifications@yourdomain.com
EMAIL_FROM_NAME=Your Company
EMAIL_TIMEOUT=30
```

| Variable | Required | Purpose |
| :--- | :--- | :--- |
| `SENDGRID_API_KEY` | yes | SendGrid Mail Send API key (not an email login) |
| `EMAIL_FROM` | no | Default from address (must be a verified sender) |
| `EMAIL_FROM_NAME` | no | Default from display name |
| `EMAIL_TIMEOUT` | no | HTTP timeout in seconds (default `30`) |
| `SENDGRID_API_URL` | no | Override API URL for EU accounts |

`EMAIL_API_KEY` is accepted as an alias for `SENDGRID_API_KEY`.

Create a key in the [SendGrid API Keys](https://app.sendgrid.com/settings/api_keys) dashboard with **Mail Send** permission. The `from` address must be a [verified sender](https://docs.sendgrid.com/ui/sending-email/sender-verification).

If the SendGrid account is hosted in the EU, also set:

```ini
SENDGRID_API_URL=https://api.eu.sendgrid.com/v3/mail/send
```

### 2. Send a plain text or HTML email

```python
from sendgrid_mailkit import EmailClient

client = EmailClient()

client.send(
    to="recipient@example.com",
    subject="Welcome to Our Platform",
    body="Hello! Thank you for joining us.",
)
```

Inline `html`, `body`, and `subject` are Jinja2 templates. Pass `data` to fill `{{ variables }}` and `{% for %}` loops:

```python
client.send(
    to="user@example.com",
    subject="Your order #{{ order_id }} is confirmed",
    html="<h1>Hi {{ name }}</h1>",
    data={"name": "John", "order_id": "ORD-12345"},
)
```

---

## Templates

Users do not need to memorize `data` keys. Ask the client:

```python
from sendgrid_mailkit import EmailClient

client = EmailClient()

print(client.describe_template("welcome"))
print(client.describe_template("welcome").example_data())
```

`help(client.send)` also lists every built-in template and its required keys.
If a required key is missing, `send()` raises `EmailTemplateError` with the
example `data` dict in the message.

| Template | Required `data` | Optional `data` |
| :--- | :--- | :--- |
| `welcome` | `name`, `company_name`, `year` | `action_url` |
| `reset_password` | `name`, `company_name`, `reset_url`, `year` | `expires_in` |
| `verify_account` | `name`, `company_name`, `verification_url`, `year` | `expires_in` |
| `getting_started` | `name`, `company_name`, `year` | `action_url`, `support_email`, `step_1`–`step_5` |

Sending a built-in template without a required key raises `EmailTemplateError` and includes the example payload.

### Welcome

```python
from sendgrid_mailkit import EmailClient

client = EmailClient()

client.send(
    to="user@example.com",
    subject="Welcome to FireCompass!",
    template="welcome",
    data={
        "name": "Jane Doe",
        "company_name": "FireCompass",
        "year": 2026,
        "action_url": "https://app.firecompass.com/dashboard",
    },
)
```

### Getting started (AI Agent)

```python
client.send(
    to="user@example.com",
    subject="Run your first assessment",
    template="getting_started",
    data={
        "name": "Jane",
        "company_name": "FireCompass",
        "year": 2026,
        "action_url": "https://app.example.com/login",
        "support_email": "support@example.com",
    },
)
```

### Custom templates

```python
from pathlib import Path
from sendgrid_mailkit import EmailClient

client = EmailClient(template_directory=Path("./my_custom_templates"))

client.send(
    to="customer@example.com",
    subject="Your Invoice is Ready",
    template="monthly_invoice",
    data={
        "customer_name": "Acme Corp",
        "invoice_number": "INV-2026-001",
        "amount_due": "$149.00",
    },
)
```

---

## Programmatic configuration

```python
from sendgrid_mailkit import EmailClient, EmailConfig

# No SMTP host, username, or password — only the API key.
config = EmailConfig(
    api_key="SG.your-sendgrid-api-key",
    from_email="no-reply@company.com",
    from_name="My Company",
)

client = EmailClient(config=config)
```

If you pass `config=` like this, you do not need `SENDGRID_API_KEY` in the environment.

---

## Exception handling

```
EmailError (Base)
├── EmailConfigurationError
├── EmailValidationError
├── EmailTemplateError
└── EmailSendError
    ├── EmailConnectionError
    ├── EmailAuthenticationError
    ├── EmailTimeoutError
    └── EmailRecipientsRefusedError
```

```python
from sendgrid_mailkit import (
    EmailClient,
    EmailAuthenticationError,
    EmailConnectionError,
    EmailRecipientsRefusedError,
    EmailTimeoutError,
    EmailValidationError,
    EmailTemplateError,
    EmailSendError,
    EmailError,
)

client = EmailClient()

try:
    client.send(
        to="client@example.com",
        subject="Important Update",
        template="welcome",
        data={"name": "Alice", "company_name": "Acme Inc."},
    )
except EmailValidationError as exc:
    print(f"Invalid email input on field '{exc.field}': {exc}")
except EmailTemplateError as exc:
    print(f"Template error ({exc.template_name}): {exc}")
except EmailAuthenticationError as exc:
    print(f"SendGrid API key was rejected: {exc}")
except EmailConnectionError as exc:
    print(f"Could not reach SendGrid ({exc.host}): {exc}")
except EmailTimeoutError as exc:
    print(f"Request timed out after {exc.timeout}s: {exc}")
except EmailRecipientsRefusedError as exc:
    print(f"SendGrid refused recipients {exc.recipients}: {exc}")
except EmailSendError as exc:
    print(f"Failed to send email: {exc}")
except EmailError as exc:
    print(f"Email SDK error: {exc}")
```

---

## Logging

The package emits no logs until your application configures logging (PEP 282).

```python
import logging
import sys

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    handlers=[logging.StreamHandler(sys.stdout)],
)

logging.getLogger("sendgrid_mailkit").setLevel(logging.DEBUG)
```

The API key is masked in `repr()` (`***`) and is never written to log output.

---

## Running tests

```bash
pip install -e ".[dev]"
pytest tests/ -v
```

---

## Publishing to PyPI

```bash
python -m build
twine check dist/*
twine upload dist/*
```

GitHub Actions also publishes on a `v*` tag when PyPI Trusted Publishing is configured.

---

## License

Distributed under the [MIT License](LICENSE).
