Metadata-Version: 2.4
Name: flanque
Version: 0.2.0
Summary: Official Flanque e-mail API SDK: send transactional e-mail, query events and verify webhooks.
Author-email: Flanque <destek@flanque.com>
License-Expression: MIT
Project-URL: Homepage, https://flanque.com
Project-URL: Documentation, https://flanque.com/docs/sdk
Project-URL: Changelog, https://flanque.com/docs/sdk#changelog
Keywords: flanque,email,e-posta,transactional,webhooks,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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: 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
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: build>=1; extra == "dev"
Requires-Dist: twine>=4; extra == "dev"
Dynamic: license-file

# flanque

Official Python SDK for the [Flanque](https://flanque.com) e-mail API. Standard library only (`urllib`), Python 3.9+, fully type-hinted (`py.typed`).

[Türkçe](#türkçe) · [English](#english)

---

## English

### Install

```bash
pip install flanque
```

### Quick start

```python
import os
from flanque import Flanque

client = Flanque(api_key=os.environ["FLANQUE_API_KEY"])

message = client.messages.send(
    from_="Firma <info@firma.com>",
    to="musteri@example.com",
    subject="Your order is confirmed",
    html="<h1>Thank you!</h1><p>Order no: 12345</p>",
    tags=["order", "confirmation"],
    idempotency_key="order-12345",
)

print(message.id, message.status)  # 8f3a… queued
```

#### Options

| Argument      | Default                      | Description                                                                 |
| ------------- | ---------------------------- | --------------------------------------------------------------------------- |
| `api_key`     | —                            | `flq_live_…` or `flq_test_…` (test keys queue to a sandbox, nothing is sent) |
| `base_url`    | `https://flanque.com/api/v1` | Self-hosted / local: `http://127.0.0.1:3100/api/v1`                         |
| `timeout`     | `30.0`                       | Per-request timeout in seconds                                              |
| `max_retries` | `3`                          | Extra attempts on `429` / `5xx` / network errors (0–3)                       |
| `headers`     | `{}`                         | Extra headers sent with every request                                       |
| `transport`   | `urllib`                     | Custom transport callable (tests, proxies)                                  |

### Sending

```python
# Single message (shortcut: client.send(...) == client.messages.send(...))
message = client.send(from_="info@firma.com", to=["a@example.com", "b@example.com"], subject="Hi", text="Plain text", reply_to="destek@firma.com", headers={"X-Campaign": "spring"})

# Several messages with bounded concurrency; one failure never stops the others
results = client.messages.send_batch(
    [
        {"from_": "info@firma.com", "to": "a@example.com", "subject": "Hi", "text": "…"},
        {"from_": "info@firma.com", "to": "b@example.com", "subject": "Hi", "text": "…"},
    ],
    concurrency=5,
)
for r in results:
    if r.ok:
        print(r.index, r.message.id)
    else:
        print(r.index, r.error)

# Status + delivery events of a message
detail = client.messages.get(message.id)
print(detail.status, [e.type for e in detail.events])

# Template built in the panel + variables + attachments (base64 string or bytes)
client.send(
    from_="info@firma.com", to="a@example.com", subject="Invoice {{no}}",
    template_id="tpl_…", variables={"no": "F-7", "name": "Ayşe"},
    attachments=[{"filename": "invoice.pdf", "content": pdf_bytes, "content_type": "application/pdf"}],
)

# Recent messages (filters: status, to)
recent = client.messages.list(limit=20, status="bounced")
```

Limits enforced by the API: up to 50 recipients, 10 tags, 20 custom `X-` headers, 50 variables, 10 attachments, 10 MB body + attachments. `idempotency_key` (max 120 chars) makes retries safe: the same key returns the previous result (`message.idempotent is True`) instead of queueing a second message.

Responses are dataclasses (`Message`, `MessageDetail`, `Event`, `Page`); the untouched server JSON is available as `.raw`.

### Events

```python
# One page (limit ≤ 100)
page = client.events.list(type="bounced", limit=50, page=1)
print(page.meta.total, [e.to for e in page])

# Walk every page
for event in client.events.iterate(message_id=message.id):
    print(event.type, event.occurred_at)

# Custom event that starts automation flows (e.g. cart_abandoned)
client.events.track(type="cart_abandoned", email="musteri@example.com", data={"total": 249.9})
```

### Contacts and lists

```python
contacts = client.contacts.list(status="subscribed", q="ada")
contact = client.contacts.create(email="ada@example.com", first_name="Ada", consent_source="api")
client.contacts.update(contact["id"], tags=["vip"])
client.contacts.delete(contact["id"])

lists = client.lists.list()
detail = client.lists.get(lists[0]["id"], limit=100)  # {"list": ..., "members": [...], "meta": PageMeta}
```

### Webhook verification

Flanque signs every webhook with `X-Flanque-Signature: t=<ms>,v1=<hex>` where `v1 = HMAC-SHA256(secret, "<t>.<rawBody>")`. Always verify against the **raw** request body.

```python
import os
from flask import Flask, abort, request
from flanque import verify_webhook_signature

app = Flask(__name__)

@app.post("/hooks/flanque")
def flanque_hook():
    if not verify_webhook_signature(request.get_data(), request.headers.get("X-Flanque-Signature"), os.environ["FLANQUE_WEBHOOK_SECRET"], tolerance_ms=300_000):
        abort(401)
    event = request.get_json()
    return "", 200
```

`client.webhooks.verify(...)` is the same function; `construct_webhook_event(raw_body, header, secret)` verifies and returns the parsed event in one step (raises `FlanqueError` with `code == "SIGNATURE_INVALID"`). Django: use `request.body`; FastAPI: `await request.body()`.

### Error handling

Every failure is a `FlanqueError` with `code`, `status` (0 when no response was received), `fields` (per-field validation messages) and `request_id`.

```python
from flanque import Flanque, FlanqueError

try:
    client.send(from_="info@firma.com", to="not-an-email", subject="Hi", text="…")
except FlanqueError as err:
    print(err.code, err.status, err.message, err.fields, err.request_id)
    # BAD_INPUT 400 Alanları kontrol edin. {'to': 'Geçerli bir alıcı adresi gerekli'} req_…
    if err.is_retryable:
        ...  # 429 / 5xx / network — the SDK already retried up to max_retries
```

Common codes: `BAD_INPUT` (400), `UNAUTHORIZED` (401), `FORBIDDEN` / `DOMAIN_NOT_VERIFIED` (403), `QUOTA` (402), `NOT_FOUND` (404), `RATE_LIMITED` (429), `INTERNAL` (5xx); client-side: `TIMEOUT`, `NETWORK_ERROR`, `INVALID_RESPONSE`, `SIGNATURE_INVALID`.

### Retries

`429` and `5xx` responses are retried with exponential backoff (0.5 s, 1 s, 2 s, ±25 % jitter, honours `Retry-After`) up to `max_retries`. Network errors and timeouts are retried only for `GET` / `DELETE` requests or for `send()` calls that carry an `idempotency_key`, so a message can never be queued twice.

### Low-level access

```python
res = client.request("GET", "/events", query={"limit": 5})
print(res.status, res.request_id, res.meta, res.data)
```

---

## Türkçe

### Kurulum

```bash
pip install flanque
```

### Hızlı başlangıç

```python
import os
from flanque import Flanque

client = Flanque(api_key=os.environ["FLANQUE_API_KEY"])

message = client.messages.send(
    from_="Firma <info@firma.com>",
    to="musteri@example.com",
    subject="Siparişiniz onaylandı",
    html="<h1>Teşekkürler!</h1><p>Sipariş no: 12345</p>",
    tags=["order", "confirmation"],
    idempotency_key="order-12345",
)

print(message.id, message.status)  # 8f3a… queued
```

Seçenekler: `api_key` (zorunlu), `base_url` (varsayılan `https://flanque.com/api/v1`; yerel için `http://127.0.0.1:3100/api/v1`), `timeout` (30 sn), `max_retries` (3), `headers`, `transport`. Test anahtarı (`flq_test_…`) iletiyi sandbox'a kuyruklar, gerçek gönderim yapmaz.

### Gönderim

- `client.send(...)` / `client.messages.send(...)` — tek ileti; `to` dize ya da en fazla 50 adresli liste, `html` ve/veya `text` zorunlu, `reply_to`, yalnız `X-` önekli `headers` (≤ 20), `tags` (≤ 10), `idempotency_key` (≤ 120 karakter).
- `client.messages.send_batch([...], concurrency=5)` — sınırlı eşzamanlılıkla çoklu gönderim; her öğe için `BatchResult(index, ok, message | error)` döner.
- `client.messages.get(id)` — durum ve teslimat olayları (`detail.events`).
- `template_id` (panel/galeri şablonu; `html` boşsa gövde şablondan üretilir), `variables` (`{{ad}}` yer tutucuları, ≤ 50) ve `attachments` (`[{"filename", "content": base64 | bytes, "content_type"?, "cid"?}]`, ≤ 10; gövde + ekler ≤ 10 MB).
- `client.messages.list(page=, limit=, status=, to=)` — sayfalı ileti listesi.

Yanıtlar dataclass'tır (`Message`, `MessageDetail`, `Event`, `Page`); ham sunucu JSON'u `.raw` içindedir. Aynı `idempotency_key` ile tekrarlanan istek yeni ileti oluşturmaz.

### Olaylar

- `client.events.list(page=, limit=, type=, message_id=)` → `Page` (`.data`, `.meta.total/page/limit/pages`)
- `for e in client.events.iterate(type="bounced")` — tüm sayfalar
- `client.events.track(type="cart_abandoned", email=..., data={...})` — otomasyon tetikleyen özel olay

### Kişiler ve listeler

`client.contacts.list/get/create/update/delete`, `client.lists.list/get/create/update/delete` (sözlük döner).

### Webhook doğrulama

Başlık `X-Flanque-Signature: t=<ms>,v1=<hex>`; imza `HMAC-SHA256(secret, "<t>.<hamGövde>")`. Her zaman **ham** gövdeyi kullanın (Flask `request.get_data()`, Django `request.body`, FastAPI `await request.body()`).

```python
from flanque import verify_webhook_signature

if not verify_webhook_signature(raw_body, request.headers.get("X-Flanque-Signature"), os.environ["FLANQUE_WEBHOOK_SECRET"], tolerance_ms=300_000):
    abort(401)
```

`construct_webhook_event(raw_body, header, secret)` doğrular ve olay sözlüğünü döner; geçersizse `FlanqueError` (`code == "SIGNATURE_INVALID"`) fırlatır.

### Hata yakalama

Tüm hatalar `FlanqueError`'dır: `code`, `status` (yanıt alınamadıysa 0), `fields`, `request_id`, `is_retryable`.

```python
try:
    client.send(from_="info@firma.com", to="gecersiz", subject="Merhaba", text="…")
except FlanqueError as err:
    print(err.code, err.status, err.fields)  # BAD_INPUT 400 {'to': 'Geçerli bir alıcı adresi gerekli'}
```

### Yeniden deneme

`429` ve `5xx` yanıtları üstel bekleme ile (0,5 s, 1 s, 2 s; `Retry-After` dikkate alınır) en fazla `max_retries` kez yinelenir. Ağ hatası ve zaman aşımı yalnız `GET`/`DELETE` isteklerinde ya da `idempotency_key` taşıyan gönderimlerde yinelenir; ileti asla iki kez kuyruğa girmez.

## License

MIT
