Metadata-Version: 2.4
Name: django-email-ledger
Version: 0.1.0
Summary: Reusable Django email attempt tracking with Anymail provider IDs
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: Django>=4.2
Requires-Dist: django-templated-email
Requires-Dist: django-anymail[mailgun]
Provides-Extra: dev
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"

# django-email-ledger

Reusable Django email backend tracking one attempt per unique To/Cc/Bcc recipient.
Stores a shared UUID reference, RFC Message-ID, recipient, purpose, subject, backend,
attempt/completion times, nullable success, error, and Anymail provider message ID
(including Mailgun IDs). Bodies and attachments are not stored. Subjects, recipient
addresses and provider errors may contain personal data; restrict admin access and
apply your application's retention policy.

## Installation

```sh
pip install django-email-ledger==0.1.0
```

Before the first release, install this directory with pip instead.

```python
INSTALLED_APPS += ['django_email_ledger']
EMAIL_BACKEND = 'django_email_ledger.backends.EmailBackend'
EMAIL_LEDGER_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
```

Run `python manage.py migrate`. For Mailgun, use
`django_email_ledger.config.mailgun_settings(api_key, sender_domain, api_url)`;
it returns EMAIL_BACKEND, EMAIL_LEDGER_BACKEND and ANYMAIL settings.
Add `anymail` to INSTALLED_APPS when using Mailgun.

Set `message.email_purpose`, use `with email_purpose('password_reset'):`, or import
`send_templated_mail` from `django_email_ledger.api` to use the template name as
purpose. Unannotated third-party messages use their subject, then `unspecified`.
`email_statistics()` returns attempted, successful, failed, pending and
success_percent over the last 24 hours (None percent when no attempts).

## Read-only Django admin

With `django.contrib.admin` and `django_email_ledger` installed, the library
automatically registers **Email ledger → Email attempts**. No application-specific
admin code is needed. Superusers can view it; other staff need the **Can view email
attempt** permission (assign it to the user or a group).

The list includes recipient, subject, purpose, result and provider ID. Search by
recipient, subject, purpose, reference, message/provider ID or error; filter by
result, backend or date. Open a row to inspect every stored field, including errors
and timestamps. Add, edit, delete and bulk actions are disabled, even for superusers.
Pending attempts have an unknown success value. Email bodies and attachments are
not stored and therefore are not displayed.

## Semantics and persistence

Success means backend acceptance, not delivery: Anymail `queued`/`sent` count as
successful; rejection/invalid/failed/unknown do not. Exceptions are recorded and
re-raised unless fail_silently is true. Each resend gets a new attempt reference.
No-recipient messages are not attempts. Rendering failures before reaching the
backend are not transport attempts. An interrupted send remains pending; it is
included in the denominator, never assumed successful. No automatic retries occur.

Records are written before contacting the provider. A database failure prevents
sending; a failure saving the result after sending raises and may leave a pending
record. Reconcile provider IDs before retrying an uncertain send.

By default records use the default database and participate in its transactions.
To retain records across request rollbacks, configure EMAIL_LEDGER_DATABASE with
an independent, autocommit database connection alias pointing to the same database.
limcweb does this with `email_ledger`; migrate the default database before sending.
Do not wrap that alias in atomic transactions. A separate SQLite connection is not
appropriate when a concurrent transaction holds its write lock. Isolated tests
can use the default connection instead. A physically separate audit database must
also have this app's migrations applied.

## Third-party coverage

Django packages using the configured default email backend are automatically
covered, including django-rest-registration signup, email-change and password
reset verification, and Django password-reset/admin email. A package choosing its
own backend or sending directly through an HTTP/SMTP client bypasses the ledger.
External Stripe receipts/invoices and other hosted service emails cannot be
observed by this backend. Provider webhooks/API imports can record provider-known
events with stable event IDs for deduplication, but cannot recover every attempted
send that failed before reaching the provider. No webhook endpoint is included.
The inspected django-stripe package synchronizes customer email addresses with
Stripe; it does not send local email for Stripe's hosted notifications.

## Tests and release

From this directory with the package installed:

```sh
python -m django test tests --settings=tests.settings
```

Install development tools with `python -m pip install '.[dev]'`. The `dev` extra
includes Build and Twine; normal library installations do not install these tools.
The publishing script automatically installs this extra using the selected Python
interpreter before building. Build installs the setuptools build dependency in an
isolated build environment.

`publish.ps1 -BuildOnly` builds fresh wheel/sdist files and runs strict Twine
validation. `publish.ps1 -Repository testpypi` uploads to TestPyPI;
`publish.ps1` uploads to PyPI. Use `-Python` to select a virtualenv interpreter.
Configure Twine credentials via keyring, .pypirc or TWINE_USERNAME=__token__ and
TWINE_PASSWORD. Never commit tokens. Increment the version in pyproject.toml for
each release; uploaded versions cannot be replaced. The distribution name is
subject to availability and your PyPI account permissions.

The repository root publish.ps1 delegates here. After publishing 0.1.0, replace
`./libraries/django-email-ledger` in limcweb requirements.txt with
`django-email-ledger==0.1.0`, install requirements and run migrations before
restarting workers. No publication or deployment is implied by these files.

References: [PyPA packaging guide](https://packaging.python.org/en/latest/tutorials/packaging-projects/)
and [Anymail send status](https://anymail.dev/en/stable/sending/anymail_additions/).
