Django HTML email and attachments
last modified November 22, 2026 Python 3.15
The send_mail() function covered in Django email sends a plain-text
message to a list of recipients. Real applications need more: copies to other addresses, a reply address, an
HTML version of the message, and attached files such as invoices. In this article we build such messages with
the EmailMessage and EmailMultiAlternatives classes, render them from templates,
configure several mailers with the console and file backends, send many messages over one connection, and test
the messages. The examples use Django 6.1 and Python 3.15.
The example project
The project is created with uv; the steps are explained in Django introduction.
The commands below create a project directory, install Django, generate the project with the configuration
package config, start the app orders, and create the folder demos for
demo scripts.
$ mkdir bookshop $ cd bookshop $ uv init --bare $ uv add django $ uv run django-admin startproject config . $ uv run python manage.py startapp orders $ mkdir demos
The new app is added to INSTALLED_APPS in config/settings.py; the other entries are
generated by startproject.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'orders',
]
The listings in this article are of two kinds. A listing with a solid blue border and the label Project
file is a file of the application: models, views, templates, tests, and settings. A listing with a dashed
amber border and the label Demo script is a small helper in the demos folder; it sets up
Django, runs a few lines of code, and prints the results, so that we can watch the behaviour. Demo scripts are
not part of the application; we run one from the project directory with uv run python -m
demos.name.
Mail settings
Since Django 6.1, the delivery of messages is configured with the MAILERS setting, a dictionary
of named mailers. The project template already defines the mailer default, which uses the console
backend: messages are printed to standard output instead of being sent. That is what we want while developing.
We add one setting in front of it: the sender address used when a message does not name one.
...
DEFAULT_FROM_EMAIL = 'Bookshop <shop@example.com>'
MAILERS = {
'default': {
'BACKEND': 'django.core.mail.backends.console.EmailBackend',
},
}
The DEFAULT_FROM_EMAIL value can contain a display name, written as in an email header. Without
the setting, Django uses webmaster@localhost.
Copies, reply address, and headers
The send_mail() function only accepts the subject, the body, the sender, and the recipients. The
EmailMessage class has more options; send_mail() itself is a short wrapper that
builds such a message.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.core.mail import EmailMessage
message = EmailMessage(
subject='Your order has shipped',
body='Hello Mary,\n\nyour order 1021 left our warehouse today.\n',
to=['mary@example.com'],
cc=['orders@example.com'],
bcc=['archive@example.com'],
reply_to=['support@example.com'],
headers={'X-Order-Number': '1021'},
)
print('recipients:', message.recipients())
print('sent:', message.send())
The to, cc, bcc, and reply_to arguments are lists; a plain
string raises a TypeError. The headers dictionary adds custom headers. We do not
pass from_email, so the message uses DEFAULT_FROM_EMAIL. The
recipients() method returns every address that receives the message, and send()
returns the number of messages sent.
The console backend prints the message as it would be sent. There is no Bcc header: blind copies
are delivered to the address, but the other recipients must not see it, so the address is only passed to the
mail server. The Date and Message-ID headers differ from run to run.
$ uv run python -m demos.plain recipients: ['mary@example.com', 'orders@example.com', 'archive@example.com'] Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit MIME-Version: 1.0 Subject: Your order has shipped From: Bookshop <shop@example.com> To: mary@example.com Cc: orders@example.com Reply-To: support@example.com Date: Sun, 22 Nov 2026 17:12:41 +0000 Message-ID: <179536756120.19134.10647060398747101321@universum> X-Order-Number: 1021 Hello Mary, your order 1021 left our warehouse today. ------------------------------------------------------------------------------- sent: 1
HTML and plain text
An HTML email should always carry a plain-text version too. Some mail clients show only text, some users
prefer it, and spam filters treat HTML-only messages with suspicion. The EmailMultiAlternatives
class sends the body as the plain-text part and adds other versions of the same content with
attach_alternative().
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.core.mail import EmailMultiAlternatives
text = 'Hello Mary,\n\nyour order 1021 is confirmed.\n'
html = '<p>Hello Mary,</p>\n<p>your order <b>1021</b> is confirmed.</p>\n'
message = EmailMultiAlternatives(
subject='Order 1021 confirmed',
body=text,
to=['mary@example.com'],
)
message.attach_alternative(html, 'text/html')
message.send()
The attach_alternative() method takes the content and its MIME type. The mail client picks the
best version it can display, normally the last one, so the HTML part goes after the text.
The message is now of the type multipart/alternative. Its parts are separated by the boundary
string from the Content-Type header: first the plain text, then the HTML.
$ uv run python -m demos.alternative MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="===============6658308538670105706==" Subject: Order 1021 confirmed From: Bookshop <shop@example.com> To: mary@example.com Date: Sun, 22 Nov 2026 17:12:41 +0000 Message-ID: <179536756142.19145.16602004485083630484@universum> --===============6658308538670105706== Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Hello Mary, your order 1021 is confirmed. --===============6658308538670105706== Content-Type: text/html; charset="utf-8" Content-Transfer-Encoding: 7bit MIME-Version: 1.0 <p>Hello Mary,</p> <p>your order <b>1021</b> is confirmed.</p> --===============6658308538670105706==-- -------------------------------------------------------------------------------
The order model
Writing HTML inside Python strings does not scale. We will send order confirmations built from templates, so we need orders first. An order has a number, a customer, an email address, and several items.
from django.db import models
class Order(models.Model):
number = models.PositiveIntegerField(unique=True)
customer = models.CharField(max_length=100)
email = models.EmailField()
created = models.DateTimeField(auto_now_add=True)
def total(self):
return sum(item.total() for item in self.items.all())
def __str__(self):
return f'Order {self.number}'
class Item(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items')
title = models.CharField(max_length=200)
quantity = models.PositiveSmallIntegerField(default=1)
price = models.DecimalField(max_digits=8, decimal_places=2)
def total(self):
return self.quantity * self.price
def __str__(self):
return self.title
The total() methods compute the price of an item and of the whole order. The
related_name='items' argument lets us write order.items.all(). We create and apply
the migrations.
$ uv run python manage.py makemigrations orders
Migrations for 'orders':
orders/migrations/0001_initial.py
+ Create model Order
+ Create model Item
$ uv run python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, orders, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying orders.0001_initial... OK
Applying sessions.0001_initial... OK
Sample data
A demo script fills the database with two orders. The customer name with an apostrophe is chosen on purpose; we will see why in the next section.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from decimal import Decimal
from orders.models import Item, Order
Order.objects.all().delete()
order = Order.objects.create(number=1021, customer="Mary O'Neil",
email='mary@example.com')
Item.objects.create(order=order, title='Dune', quantity=1, price=Decimal('12.90'))
Item.objects.create(order=order, title='The Hobbit', quantity=2,
price=Decimal('9.50'))
order = Order.objects.create(number=1022, customer='John Smith',
email='john@example.com')
Item.objects.create(order=order, title='Emma', quantity=1, price=Decimal('7.80'))
for order in Order.objects.all():
print(order, order.customer, order.email, order.total())
The script deletes old orders first, so it can be run again. The items are deleted with their orders because
of on_delete=models.CASCADE.
$ uv run python -m demos.seed Order 1021 Mary O'Neil mary@example.com 31.90 Order 1022 John Smith john@example.com 7.80
Email templates
Both versions of the message are rendered from templates. They live in the app's templates
directory, which Django searches because APP_DIRS is True in the generated settings.
The plain-text template comes first.
{% autoescape off %}Hello {{ order.customer }},
thank you for your order {{ order.number }}.
{% for item in items %}{{ item.quantity }} x {{ item.title }} {{ item.total }} EUR
{% endfor %}
Total: {{ order.total }} EUR
Bookshop
{% endautoescape %}
Django escapes variables for HTML in every template, whatever the file extension. In a plain-text message,
Mary O'Neil would appear as Mary O'Neil, so the whole template is wrapped
in {% autoescape off %}. The loop is written on one line to keep the text free of empty lines.
The HTML version uses a table for the items.
<!DOCTYPE html>
<html lang="en">
<body style="font-family: sans-serif">
<p>Hello {{ order.customer }},</p>
<p>thank you for your order <b>{{ order.number }}</b>.</p>
<table cellpadding="4">
{% for item in items %}
<tr>
<td>{{ item.quantity }} ×</td>
<td>{{ item.title }}</td>
<td align="right">{{ item.total }} EUR</td>
</tr>
{% endfor %}
<tr><td></td><th align="left">Total</th>
<th align="right">{{ order.total }} EUR</th></tr>
</table>
<p>Bookshop</p>
</body>
</html>
Mail clients ignore or strip most of the CSS that browsers support: style sheets in the head, external files,
and modern layout. That is why HTML email still uses tables, attributes such as align, and inline
style attributes. Here, escaping stays on, because the customer name is data entered by a user.
Building the message
A module emails.py in the app builds the confirmation. Keeping the construction apart from the
sending makes the function easy to reuse in a view, a management command, or a background task, and easy to
test.
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
def confirmation_message(order):
context = {'order': order, 'items': order.items.all()}
text = render_to_string('orders/email/confirmation.txt', context)
html = render_to_string('orders/email/confirmation.html', context)
message = EmailMultiAlternatives(
subject=f'Order {order.number} confirmed',
body=text,
to=[order.email],
)
message.attach_alternative(html, 'text/html')
return message
The render_to_string() function renders a template with a context and returns a string. The same
context is used for both versions. The function returns the message without sending it; the caller decides
when and with which mailer. The demo script prints the plain-text body and one line of the HTML version.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from orders.emails import confirmation_message
from orders.models import Order
order = Order.objects.get(number=1021)
message = confirmation_message(order)
print(message.body)
html = message.alternatives[0]
print(html.mimetype)
print(html.content.splitlines()[4])
The alternatives attribute is a list of named tuples with the content and
mimetype fields. The apostrophe is kept in the text body, while the HTML version escapes it; the
escaped form is displayed correctly by the mail client.
$ uv run python -m demos.confirm Hello Mary O'Neil, thank you for your order 1021. 1 x Dune 12.90 EUR 2 x The Hobbit 19.00 EUR Total: 31.90 EUR Bookshop text/html <p>thank you for your order <b>1021</b>.</p>
Attachments
The confirmation should come with an invoice and the returns policy. The policy is a static file stored in the app.
Returns policy Books can be returned within 30 days of delivery. Send them back in the original packaging together with the order number. The refund is paid within 14 days.
The invoice is generated for every order, so it never touches the disk. We extend emails.py with
a function that writes it as CSV into memory and attach both files.
import csv
import io
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
def invoice_csv(order):
buffer = io.StringIO()
writer = csv.writer(buffer)
writer.writerow(['title', 'quantity', 'price', 'total'])
for item in order.items.all():
writer.writerow([item.title, item.quantity, item.price, item.total()])
writer.writerow(['', '', '', order.total()])
return buffer.getvalue()
def confirmation_message(order):
context = {'order': order, 'items': order.items.all()}
text = render_to_string('orders/email/confirmation.txt', context)
html = render_to_string('orders/email/confirmation.html', context)
message = EmailMultiAlternatives(
subject=f'Order {order.number} confirmed',
body=text,
to=[order.email],
)
message.attach_alternative(html, 'text/html')
message.attach(f'invoice-{order.number}.csv', invoice_csv(order), 'text/csv')
message.attach_file(settings.BASE_DIR / 'orders' / 'files' / 'returns.txt')
return message
The attach() method takes a file name, the content, and the MIME type; the content can be a
string or bytes. The attach_file() method reads a file from the disk and guesses the MIME type
from the extension, here text/plain. A binary file, such as a PDF or an image, is attached in the
same way. The invoice_csv() function writes the rows to an io.StringIO buffer with
the csv module.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from orders.emails import confirmation_message
from orders.models import Order
order = Order.objects.get(number=1021)
message = confirmation_message(order).message()
for part in message.walk():
print(part.get_content_type(), part.get_filename() or '')
for part in message.iter_attachments():
if part.get_filename().endswith('.csv'):
print(part.get_content())
The message() method builds the standard library's email.message.EmailMessage object
that is sent over the wire. The walk() method visits all parts of the tree, and
iter_attachments() only the attached files.
With attachments, the message becomes multipart/mixed. Its first part is the
multipart/alternative container with the text and HTML versions; the two attachments follow. The
CSV invoice ends with the total in the last column.
$ uv run python -m demos.parts multipart/mixed multipart/alternative text/plain text/html text/csv invoice-1021.csv text/plain returns.txt title,quantity,price,total Dune,1,12.90,12.90 The Hobbit,2,9.50,19.00 ,,,31.90
Several mailers
The MAILERS setting can define more than one mailer. A project might send transactional email
through one provider and newsletters through another. We add a mailer named archive that uses the
file backend; it writes the messages into files in a directory.
...
DEFAULT_FROM_EMAIL = 'Bookshop <shop@example.com>'
MAILERS = {
'default': {
'BACKEND': 'django.core.mail.backends.console.EmailBackend',
},
'archive': {
'BACKEND': 'django.core.mail.backends.filebased.EmailBackend',
'OPTIONS': {
'file_path': BASE_DIR / 'sent-mail',
},
},
}
The BACKEND key names the backend class and OPTIONS holds its arguments. The file
backend requires the file_path option; it creates the directory when needed. Unknown options
raise an error instead of being ignored. The default mailer stays unchanged.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from orders.emails import confirmation_message
from orders.models import Order
order = Order.objects.get(number=1021)
message = confirmation_message(order)
print('archive:', message.send(using='archive'))
The using argument of send() selects the mailer by its name. Without it, the
default mailer is used, so the confirmation would be printed to the console.
The file backend wrote one file whose name is made of a timestamp and a number. With grep we list
the headers of the message and of its parts. The file holds the complete message as it would be sent to a mail
server, so it can be inspected in a text editor too.
$ uv run python -m demos.archive archive: 1 $ ls sent-mail 20261122-171243-136102800335136.log $ grep -E '^(Subject|To|Content-Type|Content-Disposition):' sent-mail/*.log Content-Type: multipart/mixed; boundary="===============6209193513637916518==" Subject: Order 1021 confirmed To: mary@example.com Content-Type: multipart/alternative; Content-Type: text/plain; charset="utf-8" Content-Type: text/html; charset="utf-8" Content-Type: text/csv; charset="utf-8" Content-Disposition: attachment; filename="invoice-1021.csv" Content-Type: text/plain; charset="utf-8" Content-Disposition: attachment; filename="returns.txt"
Sending a newsletter
The send_mass_mail() function sends several plain-text messages at once. It takes a sequence of
tuples, each with a subject, a body, a sender, and a list of recipients.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.core.mail import send_mass_mail
subscribers = ['mary@example.com', 'john@example.com', 'lucy@example.com']
body = 'New this week: three classics in a new translation.'
datatuple = [
('Bookshop news', body, None, [address]) for address in subscribers
]
print('sent:', send_mass_mail(datatuple, using='archive'))
Each subscriber gets a separate message, so the addresses are not disclosed to the other subscribers. The
sender None means DEFAULT_FROM_EMAIL. The function opens one connection and sends
all the messages over it. With the file backend, a connection is a file: all three messages end up in a single
file. Before the run, we remove the sent-mail directory.
$ uv run python -m demos.newsletter sent: 3 $ ls sent-mail 20261122-171243-140249041696624.log $ grep -c '^Subject: Bookshop news' sent-mail/*.log 3
One connection or many
Calling send() in a loop is the obvious alternative. Each call creates a new backend instance and
opens a new connection.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.core.mail import EmailMessage
subscribers = ['mary@example.com', 'john@example.com', 'lucy@example.com']
for address in subscribers:
message = EmailMessage('Bookshop news', 'New this week: ...', to=[address])
message.send(using='archive')
The loop produced three files, one per connection. With the SMTP backend, each connection means a TCP connection, a TLS handshake, and a login. That is acceptable for an occasional message, but slow for a list of subscribers, and some providers limit the number of connections per minute.
$ uv run python -m demos.loop $ ls sent-mail 20261122-171244-138250927159824.log 20261122-171244-138250927462736.log 20261122-171244-138250927464016.log
Personal messages over one connection
The send_mass_mail() function cannot send HTML or attachments. To send our own message objects
over one connection, we take a mailer instance from mailers and call its
send_messages() method.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.core.mail import mailers
from orders.emails import confirmation_message
from orders.models import Order
messages = [confirmation_message(order) for order in Order.objects.all()]
with mailers['archive'] as mailer:
print('sent:', mailer.send_messages(messages))
The expression mailers['archive'] creates a new backend instance from the settings. Using it as a
context manager opens the connection at the start of the with block and closes it at the end,
even when an error occurs. Every order gets its own confirmation, with the customer's items and invoice.
The two confirmations were written into one file, so they travelled over one connection.
$ uv run python -m demos.customers sent: 2 $ ls sent-mail 20261122-171244-126892849675104.log $ grep -E '^(Subject|To):' sent-mail/*.log Subject: Order 1021 confirmed To: mary@example.com Subject: Order 1022 confirmed To: john@example.com
Deprecated connection arguments
Code written for older Django versions reuses connections with get_connection() and the
connection argument, and suppresses errors with fail_silently. Django 6.1 still runs
such code but deprecates it in favour of mailers.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.core.mail import EmailMessage, get_connection
connection = get_connection()
message = EmailMessage('Bookshop news', 'New this week: ...',
to=['mary@example.com'], connection=connection)
print(type(connection).__module__)
Without a mailer argument, get_connection() returns an instance of the default mailer's backend.
The warnings are of the PendingDeprecationWarning kind, which Python hides by default; the
-W always option shows them. The replacements are mailers['name'] for a connection
and send(using='name') for a message.
$ uv run python -m demos.legacy
django.core.mail.backends.console
$ uv run python -W always -m demos.legacy
/home/user/bookshop/demos/legacy.py:11: RemovedInDjango2028Warning: get_connection() is deprecated. See 'Migrating email to mailers' in Django's documentation for recommended replacements.
connection = get_connection()
/home/user/bookshop/demos/legacy.py:12: RemovedInDjango2028Warning: The 'connection' argument is deprecated. Switch to the 'using' argument with a MAILERS alias.
message = EmailMessage('Bookshop news', 'New this week: ...',
django.core.mail.backends.console
Testing email
Tests must not send real email. The test runner replaces the backend of every mailer with the in-memory
backend, which stores the messages in the list django.core.mail.outbox. The list is emptied
before each test.
from decimal import Decimal
from django.core import mail
from django.test import TestCase
from .emails import confirmation_message
from .models import Item, Order
class ConfirmationTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.order = Order.objects.create(number=7, customer="Mary O'Neil",
email='mary@example.com')
Item.objects.create(order=cls.order, title='Dune', price=Decimal('12.90'))
def test_text_and_html(self):
confirmation_message(self.order).send()
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertEqual(message.subject, 'Order 7 confirmed')
self.assertEqual(message.to, ['mary@example.com'])
self.assertIn("Mary O'Neil", message.body)
self.assertEqual(message.alternatives[0].mimetype, 'text/html')
self.assertTrue(message.body_contains('12.90 EUR'))
def test_attachments(self):
confirmation_message(self.order).send(using='archive')
message = mail.outbox[0]
names = [attachment.filename for attachment in message.attachments]
self.assertEqual(names, ['invoice-7.csv', 'returns.txt'])
self.assertIn('Dune,1,12.90,12.90', message.attachments[0].content)
The first test checks the subject, the recipient, and both versions of the body. The
body_contains() method returns True only if the text occurs in the body and in every
text/* alternative. The second test sends with the archive mailer. The message still
lands in mail.outbox and no file is written, because the file backend was replaced as well. Each
attachment is a named tuple with the filename, content, and mimetype
fields.
$ uv run python manage.py test orders Found 2 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). .. ---------------------------------------------------------------------- Ran 2 tests in 0.013s OK Destroying test database for alias 'default'...
Source
Django documentation: Sending email
Django documentation: MAILERS setting
Python documentation: email.message
In this article we have built Django email messages with copies, a reply address, and custom headers, sent
HTML and plain-text versions rendered from templates, attached generated and stored files, configured a second
mailer with the file backend, sent many messages over one connection, and tested the messages with
mail.outbox. Related articles are Django email, Django templates, Django testing, and Celery with Django, which sends email from a background task.
Author
List all Django tutorials.