nh3 - HTML sanitization library for rendering HTML emails safely in Django admin
Installation
pip install django-post_office
Add post_office to your INSTALLED_APPS in django's settings.py:
INSTALLED_APPS = (
# other apps
'post_office',
)
Run migrate:
python manage.py migrate
Finally, tell Django to hand outgoing email to post_office. How you do this
depends on your Django version, because Django 6.1 replaces EMAIL_BACKEND
with MAILERS:
MAILERS['default'] is where your app queues
email; DEFAULT_MAILER names the mailer
post_office delivers it through.
Both paths let you route individual emails to other backends — see
Custom Email Backends.
Quickstart
Send a simple email is really easy:
from post_office import mail
mail.send(
'recipient@example.com', # List of email addresses also accepted
'from@example.com',
subject='My email',
message='Hi there!',
html_message='Hi <strong>there</strong>!',
)
If you want to use templates, ensure that Django's admin interface is
enabled. Create an EmailTemplate instance via admin and do the
following:
from post_office import mail
mail.send(
'recipient@example.com', # List of email addresses also accepted
'from@example.com',
template='welcome_email', # Could be an EmailTemplate instance or name
context={'foo': 'bar'},
)
The above command will put your email on the queue so you can use the
command in your webapp without slowing down the request/response cycle
too much. To actually send them out, run
python manage.py send_queued_mail. You can schedule this management
command to run regularly via cron:
mail.send is the most important function in this library, it takes
these arguments:
Argument
Required
Description
recipients
Yes
List of recipient email addresses
sender
No
Defaults to settings.DEFAULT_FROM_EMAIL, display name like John <john@a.com> is allowed
subject
No
Email subject (if template is not specified)
message
No
Email content (if template is not specified)
html_message
No
HTML content (if template is not specified)
template
No
EmailTemplate instance or name of template
language
No
Language in which you want to send the email in (if you have multilingual email templates).
cc
No
List of emails, will appear in cc field
bcc
No
List of emails, will appear in bcc field
attachments
No
Email attachments - a dict where the keys are the filenames and the values are files, file-like-objects or path to file
context
No
A dict, used to render templated email
headers
No
A dictionary of extra headers on the message
scheduled_time
No
A date/datetime object indicating when the email should be sent
expires_at
No
If specified, mails that are not yet sent won't be delivered after this date.
priority
No
high, medium, low or now (sent immediately)
backend
No
Alias of the backend you want to use, default will be used if not specified.
render_on_delivery
No
Setting this to True causes email to be lazily rendered during delivery. template is required when render_on_delivery is True. With this option, the full email content is never stored in the DB. May result in significant space savings if you're sending many emails using the same template.
Here are a few examples.
If you just want to send out emails without using database templates.
You can call the send command without the template argument.
from post_office import mail
mail.send(
['recipient1@example.com'],
'from@example.com',
subject='Welcome!',
message='Welcome home, {{ name }}!',
html_message='Welcome home, <b>{{ name }}</b>!',
headers={'Reply-to': 'reply@example.com'},
scheduled_time=date(2014, 1, 1),
context={'name': 'Alice'},
)
post_office is also task queue friendly. Passing now as priority
into send_mail will deliver the email right away (instead of queuing
it), regardless of how many emails you have in your queue:
from post_office import mail
mail.send(
['recipient1@example.com'],
'from@example.com',
template='welcome_email',
context={'foo': 'bar'},
priority='now',
)
This is useful if you already use something like django-rq to send emails
asynchronously and only need to store email related activities and logs.
If you want to send an email with attachments:
from django.core.files.base import ContentFile
from post_office import mail
mail.send(
['recipient1@example.com'],
'from@example.com',
template='welcome_email',
context={'foo': 'bar'},
priority='now',
attachments={
'attachment1.doc': '/path/to/file/file1.doc',
'attachment2.txt': ContentFile('file content'),
'attachment3.txt': {'file': ContentFile('file content'), 'mimetype': 'text/plain'},
},
)
Template Tags and Variables
post-office supports Django's template tags and variables. For
example, if you put Hello, {{ name }} in the subject line and pass in
{'name': 'Alice'} as context, you will get Hello, Alice as subject:
from post_office.models import EmailTemplate
from post_office import mail
EmailTemplate.objects.create(
name='morning_greeting',
subject='Morning, {{ name|capfirst }}',
content='Hi {{ name }}, how are you feeling today?',
html_content='Hi <strong>{{ name }}</strong>, how are you feeling today?',
)
mail.send(
['recipient@example.com'],
'from@example.com',
template='morning_greeting',
context={'name': 'alice'},
)
# This will create an email with the following content:
subject = ('Morning, Alice',)
content = 'Hi alice, how are you feeling today?'
content = 'Hi <strong>alice</strong>, how are you feeling today?'
Multilingual Email Templates
You can easily create email templates in various different languages.
For example:
template = EmailTemplate.objects.create(
name='hello',
subject='Hello world!',
)
# Add an Indonesian version of this template:
indonesian_template = template.translated_templates.create(language='id', subject='Halo Dunia!')
Sending an email using template in a non default language is similarly easy:
mail.send(
['recipient@example.com'],
'from@example.com',
template=template, # Sends using the default template
)
mail.send(
['recipient@example.com'],
'from@example.com',
template=template,
language='id', # Sends using Indonesian template
)
Inlined Images
The Post Office template backend collects the images an HTML email references
so they can be attached inline. Add this entry to your existing TEMPLATES list:
The tag accepts a path relative to a static files directory, an absolute path,
or a Django ImageFile object. It returns a cid: URL and collects the
corresponding attachment. Post Office attaches those images automatically
when you send an email template with post_office.mail.send().
When building a Django message yourself, call attach_related() on the same
template object you rendered. If you use
post_office.template.render_to_string(..., using='post_office'), unpack the
HTML and the list of images, then pass each image to email_message.attach().
The images are MIMEPart objects on Django 6+ and MIMEImage objects on older
Django versions.
To send an email containing both, a plain text body and some HTML with
inlined images, use the following code snippet:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
subject, body = 'Hello', 'Plain text body'
from_email, to_email = 'no-reply@example.com', 'john@example.com'
email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
template = get_template('email-template-name.html', using='post_office')
html = template.render({})
email_message.attach_alternative(html, 'text/html')
template.attach_related(email_message)
email_message.send()
To send an email containing HTML with inlined images, but without a
plain text body, use this code snippet:
By default, post_office delivers email through Django's smtp.EmailBackend.
You can define several backends under aliases and pick one per email. Where the
aliases are configured depends on your Django version — for example, to add
django-ses:
Aliases are keys of MAILERS; POST_OFFICE['BACKENDS']
is ignored. Emails without a backend use DEFAULT_MAILER.
Sending is the same on both:
# Delivered through `default` (Django < 6.1) or `DEFAULT_MAILER` (Django >= 6.1)
mail.send(
['recipient@example.com'],
'from@example.com',
subject='Hello',
)
# Delivered through the `ses` backend
mail.send(
['recipient@example.com'],
'from@example.com',
subject='Hello',
backend='ses',
)
Notes for MAILERS:
Django 6.1 replaces EMAIL_BACKEND and the other EMAIL_* settings with
MAILERS; the old settings keep working until Django 7.0, with deprecation
warnings.
MAILERS['default'] is post_office itself, so it cannot deliver anything —
sending through it would only requeue the email. Any alias that points at
post_office.EmailBackend is redirected to DEFAULT_MAILER on delivery, and
post_office raises InvalidMailer if DEFAULT_MAILER is unset, missing
from MAILERS, or is itself a post_office backend.
post_office reads its configuration from POST_OFFICE, never from a
mailer's OPTIONS; giving a post_office.EmailBackend mailer any OPTIONS
raises InvalidMailer.
Management Commands
send_queued_mail - send queued emails, those aren't successfully
sent will be marked as failed. Accepts the following arguments:
Argument
Description
--processes or -p
Number of parallel processes to send email. Defaults to 1
--lockfile or -L
Full path to file used as lock file. Defaults to /tmp/post_office.lock
cleanup_mail - delete all emails created before an X number of
days (defaults to 90).
Argument
Description
--days or -d
Email older than this argument will be deleted. Defaults to 90
--delete-attachments
Flag to delete orphaned attachment records and files on disk. If not specified, attachments won't be deleted.
You may want to set these up via cron to run regularly:
This section outlines all the settings and configurations that you can
put in Django's settings.py to fine tune post-office's behavior.
Webhook Handlers (Not Yet Released)
Webhook Handlers are still in beta, use at your own risk.
post_office ships with webhook handlers for AWS SES and SparkPost. These handlers
parse ESP (Email Service Provider) webhook payloads into normalized ESPEvent objects
and call handle_events() so you can implement your own persistence logic.
from post_office.webhooks import SESWebhookHandler, SparkPostWebhookHandler, ESPEvent
ESPEvent
Each webhook event is normalized into an ESPEvent object:
ESPEvent(
raw_event='delivered', # raw ESP event name
delivery_status=RecipientDeliveryStatus.DELIVERED,
recipient='user@example.com', # recipient email
message_id='<abc123@example.com>', # message-id header or provider id
timestamp=timezone.now(), # datetime if available
subject='Hello', # subject if provided
to_addresses=['a@example.com'], # all recipients if provided
)
The delivery_status field uses RecipientDeliveryStatus with the following values:
ACCEPTED
DELIVERED
OPENED
CLICKED
DEFERRED
SOFT_BOUNCED
UNDETERMINED_BOUNCED
HARD_BOUNCED
SPAM_COMPLAINT
UNSUBSCRIBED
SESWebhookHandler
Handles AWS SES notifications via SNS. Supports delivery, bounce (soft/hard/undetermined),
and complaint events.
from django.urls import path
from post_office.webhooks import SESWebhookHandler, ESPEvent
class MySESWebhookHandler(SESWebhookHandler):
def handle_events(self, events: list[ESPEvent], payload):
for event in events:
# Add your own persistence logic here.
# Example: update Email by message_id or subject.
pass
urlpatterns = [
path('webhooks/ses/', MySESWebhookHandler.as_view(), name='ses-webhook'),
]
Signature verification uses the SNS SigningCertURL and requires the cryptography
package. Set VERIFY_SIGNATURE to False for local development only.
The handler also recognizes SNS subscription confirmations; visit the SubscribeURL
from AWS to complete the subscription.
SparkPostWebhookHandler
Handles SparkPost webhook events including delivery, bounce, open, click, spam complaint,
and unsubscribe events.
from django.urls import path
from post_office.webhooks import SparkPostWebhookHandler, ESPEvent
class MySparkPostWebhookHandler(SparkPostWebhookHandler):
def handle_events(self, events: list[ESPEvent], payload):
for event in events:
# Add your own persistence logic here.
pass
urlpatterns = [
path('webhooks/sparkpost/', MySparkPostWebhookHandler.as_view(), name='sparkpost-webhook'),
]
SparkPost uses HTTP Basic Authentication. Configure USERNAME and PASSWORD to match
your SparkPost webhook settings.
File Storage
If you want Post Office to use a specific file storage for attachments, make sure to configure a
storage in the STORAGES setting in your project settings.py, then specify the storage name in
the FILE_STORAGE key. Post Office will use the default storage if this is not specified.
If you may want to limit the number of emails sent in a batch (
useful in a low memory environment), use the BATCH_SIZE argument to
limit the number of queued emails fetched in one batch. BATCH_SIZE defaults to 100.
# Put this in settings.py
POST_OFFICE = {
...
'BATCH_SIZE': 100,
}
Version 3.8 introduces a companion setting called BATCH_DELIVERY_TIMEOUT. This setting
specifies the maximum time allowed for each batch to be delivered, this is useful to guard against
cases where delivery process never terminates. Defaults to 180.
If you send a large number of emails in a single batch on a slow connection, consider increasing this number.
# Put this in settings.py
POST_OFFICE = {
...
'BATCH_DELIVERY_TIMEOUT': 180,
}
Default Priority
The default priority for emails is medium, but this can be altered by
setting DEFAULT_PRIORITY. Integration with asynchronous email backends
(e.g. based on Celery) becomes trivial when set to now.
# Put this in settings.py
POST_OFFICE = {
...
'DEFAULT_PRIORITY': 'now',
}
Default Mailer
Emails sent without a backend argument are delivered through the default
backend alias. Set DEFAULT_MAILER to deliver them through a different alias
instead. On Django 6.1+ with MAILERS, where the default mailer is normally
post_office itself, this setting is required — see
Custom Email Backends.
# Put this in settings.py
POST_OFFICE = {
...
'DEFAULT_MAILER': 'smtp',
}
Lock File Name
The default lock file name is post_office, but this can be altered by setting LOCK_FILE_NAME in the configuration.
# Put this in settings.py
POST_OFFICE = {
...
'LOCK_FILE_NAME': 'custom_lock_file',
}
Override Recipients
Defaults to None. This option is useful if you want to redirect all
emails to specified a few email for development purposes.
# Put this in settings.py
POST_OFFICE = {
...
'OVERRIDE_RECIPIENTS': ['to@example.com', 'to2@example.com'],
}
Message-ID
The SMTP standard requires that each email contains a unique Message-ID. Typically the Message-ID consists of two parts separated by the @
symbol: The left part is a generated pseudo random number. The right
part is a constant string, typically denoting the full qualified domain
name of the sending server.
By default, Django generates such a Message-ID during email
delivery. Since django-post_office keeps track of all delivered
emails, it can be very useful to create and store this Message-ID while
creating each email in the database. This identifier then can be looked
up in the Django admin backend.
To enable this feature, add this to your Post-Office settings:
# Put this in settings.py
POST_OFFICE = {
...
'MESSAGE_ID_ENABLED': True,
}
It can further be fine tuned, using for instance another full qualified
domain name:
# Put this in settings.py
POST_OFFICE = {
...
'MESSAGE_ID_ENABLED': True,
'MESSAGE_ID_FQDN': 'example.com',
}
Otherwise, if MESSAGE_ID_FQDN is unset (the default),
django-post_office falls back to the DNS name of the server, which
is determined by the network settings of the host.
Retry
Not activated by default. You can automatically requeue failed email deliveries.
You can also configure failed deliveries to be retried after a specific time interval.
# Put this in settings.py
POST_OFFICE = {
...
'MAX_RETRIES': 4,
'RETRY_INTERVAL': datetime.timedelta(minutes=15), # Schedule to be retried 15 minutes later
}
Log Level
Logs are stored in the database and is browsable via Django admin.
The default log level is 2 (logs both successful and failed deliveries)
This behavior can be changed by setting LOG_LEVEL.
# Put this in settings.py
POST_OFFICE = {
...
'LOG_LEVEL': 1, # Log only failed deliveries
}
The different options are:
0 logs nothing
1 logs only failed deliveries
2 logs everything (both successful and failed delivery attempts)
Sending Order
The default sending order for emails is -priority, but this can be
altered by setting SENDING_ORDER. For example, if you want to send
queued emails in FIFO order :
# Put this in settings.py
POST_OFFICE = {
...
'SENDING_ORDER': ['created'],
}
Context Field Serializer
If you need to store complex Python objects for deferred rendering (i.e.
setting render_on_delivery=True), you can specify your own context
field class to store context variables. For example if you want to use
django-picklefield:
# Put this in settings.py
POST_OFFICE = {
...
'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField',
}
CONTEXT_FIELD_CLASS defaults to django.db.models.JSONField.
Logging
You can configure post-office's logging from Django's settings.py.
For example:
post-office >= 3.0 allows you to use multiple threads to dramatically
speed up the speed at which emails are sent. By default, post-office
uses 5 threads per process. You can tweak this setting by changing
THREADS_PER_PROCESS setting.
This may dramatically increase the speed of bulk email delivery,
depending on which email backends you use. In my tests, multi threading
speeds up email backends that use HTTP based (REST) delivery mechanisms
but doesn't seem to help SMTP based backends.
# Put this in settings.py
POST_OFFICE = {
...
'THREADS_PER_PROCESS': 10,
}
Performance
Caching
if Django's caching mechanism is configured, post_office will cache
EmailTemplate instances . If for some reason you want to disable
caching, set POST_OFFICE_CACHE to False in settings.py:
## All cache key will be prefixed by post_office:template:
## To turn OFF caching, you need to explicitly set POST_OFFICE_CACHE to False in settings
POST_OFFICE_CACHE = False
## Optional: to use a non default cache backend, add a "post_office" entry in CACHES
CACHES = {
'post_office': {
'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
'LOCATION': '127.0.0.1:11211',
}
}
send_many()
send_many() is much more performant (generates less database queries)
when sending a large number of emails. send_many() is almost identical
to mail.send(), with the exception that it accepts a list of keyword
arguments that you'd usually pass into mail.send():
Attachments are not supported with mail.send_many().
Checking Formatting
Install the Ruff formatting hook with pre-commit install or prek install.
The hook checks staged files using the Ruff settings in pyproject.toml.
To check the whole repository, run pre-commit run --all-files or
prek run --all-files.
Running Tests
To run the test suite:
pip install -e ".[test]"
pytest
The full matrix of supported Python and Django versions is tested on CI. To run
the suite locally against a specific combination:
uv run --python 3.13 --with "django~=6.1.0" --extra test pytest
Integration with Celery
If your Django project runs in a Celery enabled configuration, you can use its worker to send out
queued emails. Compared to the solution with cron (see above), or the solution with uWSGI timers
(see below) this setup has the big advantage that queued emails are send immediately after they
have been added to the mail queue. The delivery is still performed in a separate and asynchronous
task, which prevents sending emails during the request/response-cycle.
Delivering emails through the Celery worker must be explicitly enabled:
# Put this in settings.py
POST_OFFICE = {
...
'CELERY_ENABLED': True,
}
Emails will then be delivered immediately after they have been queued. In order to make this happen,
the project's celery.py setup shall invoke the
autodiscoverttasks
function. In case of a temporary delivery failure, we might want retrying to send those emails by a
periodic task. This can be scheduled with a simple
Celery beat configuration,
for instance through
The email queue now will be processed every 10 minutes. If you are using
Django Celery Beat,
then use the Django-Admin backend and add a periodic tasks for post_office.tasks.send_queued_mail.
Depending on your policy, you may also want to remove expired emails from the queue. This can be
done by adding another periodic tasks for post_office.tasks.cleanup_mail, which may run once a
week or month.
Integration with uWSGI
If setting up Celery is too daunting and you use
uWSGI as application
server, then uWSGI decorators can act as a poor men's scheduler. Just
add this short snipped to the project's wsgi.py file:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# add this block of code
try:
import uwsgidecorators
from django.core.management import call_command
@uwsgidecorators.timer(10)
def send_queued_mail(num):
"""Send queued mail every 10 seconds"""
call_command('send_queued_mail', processes=1)
except ImportError:
print('uwsgidecorators not found. Cron and timers are disabled')
Alternatively you can also use the decorator
@uwsgidecorators.cron(minute, hour, day, month, weekday). This will
schedule a task at specific times. Use -1 to signal any time, it
corresponds to the * in cron.
Please note that uwsgidecorators are available only, if the
application has been started with uWSGI. However, Django's internal
./manange.py runserver also access this file, therefore wrap the block
into an exception handler as shown above.
This configuration can be useful in environments, such as Docker
containers, where you don't have a running cron-daemon.
Signals
Each time an email is added to the mail queue, Post Office emits a
special Django signal.
Whenever a third party application wants to be informed about this
event, it shall connect a callback function to the Post Office's signal
handler email_queued, for instance:
from django.dispatch import receiver
from post_office.signals import email_queued
@receiver(email_queued)
def my_callback(sender, emails, **kwargs):
print('Added {} mails to the sending queue'.format(len(emails)))
The Emails objects added to the queue are passed as list to the callback
handler.