| 1 |
============= |
| 2 |
Sending email |
| 3 |
============= |
| 4 |
|
| 5 |
.. module:: django.core.mail |
| 6 |
:synopsis: Helpers to easily send email. |
| 7 |
|
| 8 |
Although Python provides a mail sending interface via the :mod:`smtplib` |
| 9 |
module, Django provides a couple of light wrappers over it. These wrappers are |
| 10 |
provided to make sending email extra quick, to help test email sending during |
| 11 |
development, and to provide support for platforms that can't use SMTP. |
| 12 |
|
| 13 |
The code lives in the ``django.core.mail`` module. |
| 14 |
|
| 15 |
Quick examples |
| 16 |
============== |
| 17 |
|
| 18 |
Use :func:`send_mail` for straightforward email sending. For example, to send a |
| 19 |
plain text message:: |
| 20 |
|
| 21 |
from django.core.mail import send_mail |
| 22 |
|
| 23 |
send_mail( |
| 24 |
"Subject here", |
| 25 |
"Here is the message.", |
| 26 |
"[email protected]", |
| 27 |
["[email protected]"], |
| 28 |
fail_silently=False, |
| 29 |
) |
| 30 |
|
| 31 |
When additional email sending functionality is needed, use |
| 32 |
:class:`EmailMessage` or :class:`EmailMultiAlternatives`. For example, to send |
| 33 |
a multipart email that includes both HTML and plain text versions with a |
| 34 |
specific template and custom headers, you can use the following approach:: |
| 35 |
|
| 36 |
from django.core.mail import EmailMultiAlternatives |
| 37 |
from django.template.loader import render_to_string |
| 38 |
|
| 39 |
# First, render the plain text content. |
| 40 |
text_content = render_to_string( |
| 41 |
"templates/emails/my_email.txt", |
| 42 |
context={"my_variable": 42}, |
| 43 |
) |
| 44 |
|
| 45 |
# Secondly, render the HTML content. |
| 46 |
html_content = render_to_string( |
| 47 |
"templates/emails/my_email.html", |
| 48 |
context={"my_variable": 42}, |
| 49 |
) |
| 50 |
|
| 51 |
# Then, create a multipart email instance. |
| 52 |
msg = EmailMultiAlternatives( |
| 53 |
"Subject here", |
| 54 |
text_content, |
| 55 |
"[email protected]", |
| 56 |
["[email protected]"], |
| 57 |
headers={"List-Unsubscribe": "<mailto:[email protected]>"}, |
| 58 |
) |
| 59 |
|
| 60 |
# Lastly, attach the HTML content to the email instance and send. |
| 61 |
msg.attach_alternative(html_content, "text/html") |
| 62 |
msg.send() |
| 63 |
|
| 64 |
Mail is sent using the SMTP host and port specified in the |
| 65 |
:setting:`EMAIL_HOST` and :setting:`EMAIL_PORT` settings. The |
| 66 |
:setting:`EMAIL_HOST_USER` and :setting:`EMAIL_HOST_PASSWORD` settings, if |
| 67 |
set, are used to authenticate to the SMTP server, and the |
| 68 |
:setting:`EMAIL_USE_TLS` and :setting:`EMAIL_USE_SSL` settings control whether |
| 69 |
a secure connection is used. |
| 70 |
|
| 71 |
.. note:: |
| 72 |
|
| 73 |
The character set of email sent with ``django.core.mail`` will be set to |
| 74 |
the value of your :setting:`DEFAULT_CHARSET` setting. |
| 75 |
|
| 76 |
``send_mail()`` |
| 77 |
=============== |
| 78 |
|
| 79 |
.. function:: send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None) |
| 80 |
|
| 81 |
In most cases, you can send email using ``django.core.mail.send_mail()``. |
| 82 |
|
| 83 |
The ``subject``, ``message``, ``from_email`` and ``recipient_list`` parameters |
| 84 |
are required. |
| 85 |
|
| 86 |
* ``subject``: A string. |
| 87 |
* ``message``: A string. |
| 88 |
* ``from_email``: A string. If ``None``, Django will use the value of the |
| 89 |
:setting:`DEFAULT_FROM_EMAIL` setting. |
| 90 |
* ``recipient_list``: A list of strings, each an email address. Each |
| 91 |
member of ``recipient_list`` will see the other recipients in the "To:" |
| 92 |
field of the email message. |
| 93 |
* ``fail_silently``: A boolean. When it's ``False``, ``send_mail()`` will raise |
| 94 |
an :exc:`smtplib.SMTPException` if an error occurs. See the :mod:`smtplib` |
| 95 |
docs for a list of possible exceptions, all of which are subclasses of |
| 96 |
:exc:`~smtplib.SMTPException`. |
| 97 |
* ``auth_user``: The optional username to use to authenticate to the SMTP |
| 98 |
server. If this isn't provided, Django will use the value of the |
| 99 |
:setting:`EMAIL_HOST_USER` setting. |
| 100 |
* ``auth_password``: The optional password to use to authenticate to the |
| 101 |
SMTP server. If this isn't provided, Django will use the value of the |
| 102 |
:setting:`EMAIL_HOST_PASSWORD` setting. |
| 103 |
* ``connection``: The optional email backend to use to send the mail. |
| 104 |
If unspecified, an instance of the default backend will be used. |
| 105 |
See the documentation on :ref:`Email backends <topic-email-backends>` |
| 106 |
for more details. |
| 107 |
* ``html_message``: If ``html_message`` is provided, the resulting email will be a |
| 108 |
:mimetype:`multipart/alternative` email with ``message`` as the |
| 109 |
:mimetype:`text/plain` content type and ``html_message`` as the |
| 110 |
:mimetype:`text/html` content type. |
| 111 |
|
| 112 |
The return value will be the number of successfully delivered messages (which |
| 113 |
can be ``0`` or ``1`` since it can only send one message). |
| 114 |
|
| 115 |
``send_mass_mail()`` |
| 116 |
==================== |
| 117 |
|
| 118 |
.. function:: send_mass_mail(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None) |
| 119 |
|
| 120 |
``django.core.mail.send_mass_mail()`` is intended to handle mass emailing. |
| 121 |
|
| 122 |
``datatuple`` is a tuple in which each element is in this format:: |
| 123 |
|
| 124 |
(subject, message, from_email, recipient_list) |
| 125 |
|
| 126 |
``fail_silently``, ``auth_user`` and ``auth_password`` have the same functions |
| 127 |
as in :func:`~django.core.mail.send_mail`. |
| 128 |
|
| 129 |
Each separate element of ``datatuple`` results in a separate email message. |
| 130 |
As in :func:`~django.core.mail.send_mail`, recipients in the same |
| 131 |
``recipient_list`` will all see the other addresses in the email messages' |
| 132 |
"To:" field. |
| 133 |
|
| 134 |
For example, the following code would send two different messages to |
| 135 |
two different sets of recipients; however, only one connection to the |
| 136 |
mail server would be opened:: |
| 137 |
|
| 138 |
message1 = ( |
| 139 |
"Subject here", |
| 140 |
"Here is the message", |
| 141 |
"[email protected]", |
| 142 |
["[email protected]", "[email protected]"], |
| 143 |
) |
| 144 |
message2 = ( |
| 145 |
"Another Subject", |
| 146 |
"Here is another message", |
| 147 |
"[email protected]", |
| 148 |
["[email protected]"], |
| 149 |
) |
| 150 |
send_mass_mail((message1, message2), fail_silently=False) |
| 151 |
|
| 152 |
The return value will be the number of successfully delivered messages. |
| 153 |
|
| 154 |
``send_mass_mail()`` vs. ``send_mail()`` |
| 155 |
---------------------------------------- |
| 156 |
|
| 157 |
The main difference between :func:`~django.core.mail.send_mass_mail` and |
| 158 |
:func:`~django.core.mail.send_mail` is that |
| 159 |
:func:`~django.core.mail.send_mail` opens a connection to the mail server |
| 160 |
each time it's executed, while :func:`~django.core.mail.send_mass_mail` uses |
| 161 |
a single connection for all of its messages. This makes |
| 162 |
:func:`~django.core.mail.send_mass_mail` slightly more efficient. |
| 163 |
|
| 164 |
``mail_admins()`` |
| 165 |
================= |
| 166 |
|
| 167 |
.. function:: mail_admins(subject, message, fail_silently=False, connection=None, html_message=None) |
| 168 |
|
| 169 |
``django.core.mail.mail_admins()`` is a shortcut for sending an email to the |
| 170 |
site admins, as defined in the :setting:`ADMINS` setting. |
| 171 |
|
| 172 |
``mail_admins()`` prefixes the subject with the value of the |
| 173 |
:setting:`EMAIL_SUBJECT_PREFIX` setting, which is ``"[Django] "`` by default. |
| 174 |
|
| 175 |
The "From:" header of the email will be the value of the |
| 176 |
:setting:`SERVER_EMAIL` setting. |
| 177 |
|
| 178 |
This method exists for convenience and readability. |
| 179 |
|
| 180 |
If ``html_message`` is provided, the resulting email will be a |
| 181 |
:mimetype:`multipart/alternative` email with ``message`` as the |
| 182 |
:mimetype:`text/plain` content type and ``html_message`` as the |
| 183 |
:mimetype:`text/html` content type. |
| 184 |
|
| 185 |
``mail_managers()`` |
| 186 |
=================== |
| 187 |
|
| 188 |
.. function:: mail_managers(subject, message, fail_silently=False, connection=None, html_message=None) |
| 189 |
|
| 190 |
``django.core.mail.mail_managers()`` is just like ``mail_admins()``, except it |
| 191 |
sends an email to the site managers, as defined in the :setting:`MANAGERS` |
| 192 |
setting. |
| 193 |
|
| 194 |
Examples |
| 195 |
======== |
| 196 |
|
| 197 |
This sends a single email to [email protected] and [email protected], with them |
| 198 |
both appearing in the "To:":: |
| 199 |
|
| 200 |
send_mail( |
| 201 |
"Subject", |
| 202 |
"Message.", |
| 203 |
"[email protected]", |
| 204 |
["[email protected]", "[email protected]"], |
| 205 |
) |
| 206 |
|
| 207 |
This sends a message to [email protected] and [email protected], with them both |
| 208 |
receiving a separate email:: |
| 209 |
|
| 210 |
datatuple = ( |
| 211 |
("Subject", "Message.", "[email protected]", ["[email protected]"]), |
| 212 |
("Subject", "Message.", "[email protected]", ["[email protected]"]), |
| 213 |
) |
| 214 |
send_mass_mail(datatuple) |
| 215 |
|
| 216 |
Preventing header injection |
| 217 |
=========================== |
| 218 |
|
| 219 |
`Header injection`_ is a security exploit in which an attacker inserts extra |
| 220 |
email headers to control the "To:" and "From:" in email messages that your |
| 221 |
scripts generate. |
| 222 |
|
| 223 |
The Django email functions outlined above all protect against header injection |
| 224 |
by forbidding newlines in header values. If any ``subject``, ``from_email`` or |
| 225 |
``recipient_list`` contains a newline (in either Unix, Windows or Mac style), |
| 226 |
the email function (e.g. :func:`~django.core.mail.send_mail`) will raise |
| 227 |
``django.core.mail.BadHeaderError`` (a subclass of ``ValueError``) and, hence, |
| 228 |
will not send the email. It's your responsibility to validate all data before |
| 229 |
passing it to the email functions. |
| 230 |
|
| 231 |
If a ``message`` contains headers at the start of the string, the headers will |
| 232 |
be printed as the first bit of the email message. |
| 233 |
|
| 234 |
Here's an example view that takes a ``subject``, ``message`` and ``from_email`` |
| 235 |
from the request's POST data, sends that to [email protected] and redirects to |
| 236 |
"/contact/thanks/" when it's done:: |
| 237 |
|
| 238 |
from django.core.mail import BadHeaderError, send_mail |
| 239 |
from django.http import HttpResponse, HttpResponseRedirect |
| 240 |
|
| 241 |
|
| 242 |
def send_email(request): |
| 243 |
subject = request.POST.get("subject", "") |
| 244 |
message = request.POST.get("message", "") |
| 245 |
from_email = request.POST.get("from_email", "") |
| 246 |
if subject and message and from_email: |
| 247 |
try: |
| 248 |
send_mail(subject, message, from_email, ["[email protected]"]) |
| 249 |
except BadHeaderError: |
| 250 |
return HttpResponse("Invalid header found.") |
| 251 |
return HttpResponseRedirect("/contact/thanks/") |
| 252 |
else: |
| 253 |
# In reality we'd use a form class |
| 254 |
# to get proper validation errors. |
| 255 |
return HttpResponse("Make sure all fields are entered and valid.") |
| 256 |
|
| 257 |
.. _Header injection: http://www.nyphp.org/phundamentals/8_Preventing-Email-Header-Injection.html |
| 258 |
|
| 259 |
.. _emailmessage-and-smtpconnection: |
| 260 |
|
| 261 |
The ``EmailMessage`` class |
| 262 |
========================== |
| 263 |
|
| 264 |
Django's :func:`~django.core.mail.send_mail` and |
| 265 |
:func:`~django.core.mail.send_mass_mail` functions are actually thin |
| 266 |
wrappers that make use of the :class:`~django.core.mail.EmailMessage` class. |
| 267 |
|
| 268 |
Not all features of the :class:`~django.core.mail.EmailMessage` class are |
| 269 |
available through the :func:`~django.core.mail.send_mail` and related |
| 270 |
wrapper functions. If you wish to use advanced features, such as BCC'ed |
| 271 |
recipients, file attachments, or multi-part email, you'll need to create |
| 272 |
:class:`~django.core.mail.EmailMessage` instances directly. |
| 273 |
|
| 274 |
.. note:: |
| 275 |
This is a design feature. :func:`~django.core.mail.send_mail` and |
| 276 |
related functions were originally the only interface Django provided. |
| 277 |
However, the list of parameters they accepted was slowly growing over |
| 278 |
time. It made sense to move to a more object-oriented design for email |
| 279 |
messages and retain the original functions only for backwards |
| 280 |
compatibility. |
| 281 |
|
| 282 |
:class:`~django.core.mail.EmailMessage` is responsible for creating the email |
| 283 |
message itself. The :ref:`email backend <topic-email-backends>` is then |
| 284 |
responsible for sending the email. |
| 285 |
|
| 286 |
For convenience, :class:`~django.core.mail.EmailMessage` provides a ``send()`` |
| 287 |
method for sending a single email. If you need to send multiple messages, the |
| 288 |
email backend API :ref:`provides an alternative |
| 289 |
<topics-sending-multiple-emails>`. |
| 290 |
|
| 291 |
``EmailMessage`` Objects |
| 292 |
------------------------ |
| 293 |
|
| 294 |
.. class:: EmailMessage |
| 295 |
|
| 296 |
The :class:`~django.core.mail.EmailMessage` class is initialized with the |
| 297 |
following parameters (in the given order, if positional arguments are used). |
| 298 |
All parameters are optional and can be set at any time prior to calling the |
| 299 |
``send()`` method. |
| 300 |
|
| 301 |
* ``subject``: The subject line of the email. |
| 302 |
|
| 303 |
* ``body``: The body text. This should be a plain text message. |
| 304 |
|
| 305 |
* ``from_email``: The sender's address. Both ``[email protected]`` and |
| 306 |
``"Fred" <[email protected]>`` forms are legal. If omitted, the |
| 307 |
:setting:`DEFAULT_FROM_EMAIL` setting is used. |
| 308 |
|
| 309 |
* ``to``: A list or tuple of recipient addresses. |
| 310 |
|
| 311 |
* ``bcc``: A list or tuple of addresses used in the "Bcc" header when |
| 312 |
sending the email. |
| 313 |
|
| 314 |
* ``connection``: An :ref:`email backend <topic-email-backends>` instance. Use |
| 315 |
this parameter if you are sending the ``EmailMessage`` via ``send()`` and you |
| 316 |
want to use the same connection for multiple messages. If omitted, a new |
| 317 |
connection is created when ``send()`` is called. This parameter is ignored |
| 318 |
when using :ref:`send_messages() <topics-sending-multiple-emails>`. |
| 319 |
|
| 320 |
* ``attachments``: A list of attachments to put on the message. These can |
| 321 |
be instances of :class:`~email.mime.base.MIMEBase` or |
| 322 |
:class:`~django.core.mail.EmailAttachment`, or a tuple with attributes |
| 323 |
``(filename, content, mimetype)``. |
| 324 |
|
| 325 |
.. versionchanged:: 5.2 |
| 326 |
|
| 327 |
Support for :class:`~django.core.mail.EmailAttachment` items of |
| 328 |
``attachments`` was added. |
| 329 |
|
| 330 |
* ``headers``: A dictionary of extra headers to put on the message. The |
| 331 |
keys are the header name, values are the header values. It's up to the |
| 332 |
caller to ensure header names and values are in the correct format for |
| 333 |
an email message. The corresponding attribute is ``extra_headers``. |
| 334 |
|
| 335 |
* ``cc``: A list or tuple of recipient addresses used in the "Cc" header |
| 336 |
when sending the email. |
| 337 |
|
| 338 |
* ``reply_to``: A list or tuple of recipient addresses used in the "Reply-To" |
| 339 |
header when sending the email. |
| 340 |
|
| 341 |
For example:: |
| 342 |
|
| 343 |
from django.core.mail import EmailMessage |
| 344 |
|
| 345 |
email = EmailMessage( |
| 346 |
"Hello", |
| 347 |
"Body goes here", |
| 348 |
"[email protected]", |
| 349 |
["[email protected]", "[email protected]"], |
| 350 |
["[email protected]"], |
| 351 |
reply_to=["[email protected]"], |
| 352 |
headers={"Message-ID": "foo"}, |
| 353 |
) |
| 354 |
|
| 355 |
The class has the following methods: |
| 356 |
|
| 357 |
* ``send(fail_silently=False)`` sends the message. If a connection was |
| 358 |
specified when the email was constructed, that connection will be used. |
| 359 |
Otherwise, an instance of the default backend will be instantiated and |
| 360 |
used. If the keyword argument ``fail_silently`` is ``True``, exceptions |
| 361 |
raised while sending the message will be quashed. An empty list of |
| 362 |
recipients will not raise an exception. It will return ``1`` if the message |
| 363 |
was sent successfully, otherwise ``0``. |
| 364 |
|
| 365 |
* ``message()`` constructs a ``django.core.mail.SafeMIMEText`` object (a |
| 366 |
subclass of Python's :class:`~email.mime.text.MIMEText` class) or a |
| 367 |
``django.core.mail.SafeMIMEMultipart`` object holding the message to be |
| 368 |
sent. If you ever need to extend the |
| 369 |
:class:`~django.core.mail.EmailMessage` class, you'll probably want to |
| 370 |
override this method to put the content you want into the MIME object. |
| 371 |
|
| 372 |
* ``recipients()`` returns a list of all the recipients of the message, |
| 373 |
whether they're recorded in the ``to``, ``cc`` or ``bcc`` attributes. This |
| 374 |
is another method you might need to override when subclassing, because the |
| 375 |
SMTP server needs to be told the full list of recipients when the message |
| 376 |
is sent. If you add another way to specify recipients in your class, they |
| 377 |
need to be returned from this method as well. |
| 378 |
|
| 379 |
* ``attach()`` creates a new file attachment and adds it to the message. |
| 380 |
There are two ways to call ``attach()``: |
| 381 |
|
| 382 |
* You can pass it a single argument that is a |
| 383 |
:class:`~email.mime.base.MIMEBase` instance. This will be inserted directly |
| 384 |
into the resulting message. |
| 385 |
|
| 386 |
* Alternatively, you can pass ``attach()`` three arguments: |
| 387 |
``filename``, ``content`` and ``mimetype``. ``filename`` is the name |
| 388 |
of the file attachment as it will appear in the email, ``content`` is |
| 389 |
the data that will be contained inside the attachment and |
| 390 |
``mimetype`` is the optional MIME type for the attachment. If you |
| 391 |
omit ``mimetype``, the MIME content type will be guessed from the |
| 392 |
filename of the attachment. |
| 393 |
|
| 394 |
For example:: |
| 395 |
|
| 396 |
message.attach("design.png", img_data, "image/png") |
| 397 |
|
| 398 |
If you specify a ``mimetype`` of :mimetype:`message/rfc822`, it will also |
| 399 |
accept :class:`django.core.mail.EmailMessage` and |
| 400 |
:py:class:`email.message.Message`. |
| 401 |
|
| 402 |
For a ``mimetype`` starting with :mimetype:`text/`, content is expected to |
| 403 |
be a string. Binary data will be decoded using UTF-8, and if that fails, |
| 404 |
the MIME type will be changed to :mimetype:`application/octet-stream` and |
| 405 |
the data will be attached unchanged. |
| 406 |
|
| 407 |
In addition, :mimetype:`message/rfc822` attachments will no longer be |
| 408 |
base64-encoded in violation of :rfc:`2046#section-5.2.1`, which can cause |
| 409 |
issues with displaying the attachments in `Evolution`__ and `Thunderbird`__. |
| 410 |
|
| 411 |
__ https://bugzilla.gnome.org/show_bug.cgi?id=651197 |
| 412 |
__ https://bugzilla.mozilla.org/show_bug.cgi?id=333880 |
| 413 |
|
| 414 |
* ``attach_file()`` creates a new attachment using a file from your |
| 415 |
filesystem. Call it with the path of the file to attach and, optionally, |
| 416 |
the MIME type to use for the attachment. If the MIME type is omitted, it |
| 417 |
will be guessed from the filename. You can use it like this:: |
| 418 |
|
| 419 |
message.attach_file("/images/weather_map.png") |
| 420 |
|
| 421 |
For MIME types starting with :mimetype:`text/`, binary data is handled as in |
| 422 |
``attach()``. |
| 423 |
|
| 424 |
.. class:: EmailAttachment |
| 425 |
|
| 426 |
.. versionadded:: 5.2 |
| 427 |
|
| 428 |
A named tuple to store attachments to an email. |
| 429 |
|
| 430 |
The named tuple has the following indexes: |
| 431 |
|
| 432 |
* ``filename`` |
| 433 |
* ``content`` |
| 434 |
* ``mimetype`` |
| 435 |
|
| 436 |
Sending alternative content types |
| 437 |
--------------------------------- |
| 438 |
|
| 439 |
Sending multiple content versions |
| 440 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 441 |
|
| 442 |
It can be useful to include multiple versions of the content in an email; the |
| 443 |
classic example is to send both text and HTML versions of a message. With |
| 444 |
Django's email library, you can do this using the |
| 445 |
:class:`~django.core.mail.EmailMultiAlternatives` class. |
| 446 |
|
| 447 |
.. class:: EmailMultiAlternatives |
| 448 |
|
| 449 |
A subclass of :class:`EmailMessage` that allows additional versions of the |
| 450 |
message body in the email via the :meth:`attach_alternative` method. This |
| 451 |
directly inherits all methods (including the class initialization) from |
| 452 |
:class:`EmailMessage`. |
| 453 |
|
| 454 |
.. attribute:: alternatives |
| 455 |
|
| 456 |
A list of :class:`~django.core.mail.EmailAlternative` named tuples. This |
| 457 |
is particularly useful in tests:: |
| 458 |
|
| 459 |
self.assertEqual(len(msg.alternatives), 1) |
| 460 |
self.assertEqual(msg.alternatives[0].content, html_content) |
| 461 |
self.assertEqual(msg.alternatives[0].mimetype, "text/html") |
| 462 |
|
| 463 |
Alternatives should only be added using the :meth:`attach_alternative` |
| 464 |
method, or passed to the constructor. |
| 465 |
|
| 466 |
.. versionchanged:: 5.2 |
| 467 |
|
| 468 |
In older versions, ``alternatives`` was a list of regular tuples, |
| 469 |
as opposed to :class:`~django.core.mail.EmailAlternative` named |
| 470 |
tuples. |
| 471 |
|
| 472 |
.. method:: attach_alternative(content, mimetype) |
| 473 |
|
| 474 |
Attach an alternative representation of the message body in the email. |
| 475 |
|
| 476 |
For example, to send a text and HTML combination, you could write:: |
| 477 |
|
| 478 |
from django.core.mail import EmailMultiAlternatives |
| 479 |
|
| 480 |
subject = "hello" |
| 481 |
from_email = "[email protected]" |
| 482 |
to = "[email protected]" |
| 483 |
text_content = "This is an important message." |
| 484 |
html_content = "<p>This is an <strong>important</strong> message.</p>" |
| 485 |
msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) |
| 486 |
msg.attach_alternative(html_content, "text/html") |
| 487 |
msg.send() |
| 488 |
|
| 489 |
.. method:: body_contains(text) |
| 490 |
|
| 491 |
.. versionadded:: 5.2 |
| 492 |
|
| 493 |
Returns a boolean indicating whether the provided ``text`` is |
| 494 |
contained in the email ``body`` and in all attached MIME type |
| 495 |
``text/*`` alternatives. |
| 496 |
|
| 497 |
This can be useful when testing emails. For example:: |
| 498 |
|
| 499 |
def test_contains_email_content(self): |
| 500 |
subject = "Hello World" |
| 501 |
from_email = "[email protected]" |
| 502 |
to = "[email protected]" |
| 503 |
msg = EmailMultiAlternatives(subject, "I am content.", from_email, [to]) |
| 504 |
msg.attach_alternative("<p>I am content.</p>", "text/html") |
| 505 |
|
| 506 |
self.assertIs(msg.body_contains("I am content"), True) |
| 507 |
self.assertIs(msg.body_contains("<p>I am content.</p>"), False) |
| 508 |
|
| 509 |
.. class:: EmailAlternative |
| 510 |
|
| 511 |
.. versionadded:: 5.2 |
| 512 |
|
| 513 |
A named tuple to store alternative versions of email content. |
| 514 |
|
| 515 |
The named tuple has the following indexes: |
| 516 |
|
| 517 |
* ``content`` |
| 518 |
* ``mimetype`` |
| 519 |
|
| 520 |
Updating the default content type |
| 521 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 522 |
|
| 523 |
By default, the MIME type of the ``body`` parameter in an |
| 524 |
:class:`~django.core.mail.EmailMessage` is ``"text/plain"``. It is good |
| 525 |
practice to leave this alone, because it guarantees that any recipient will be |
| 526 |
able to read the email, regardless of their mail client. However, if you are |
| 527 |
confident that your recipients can handle an alternative content type, you can |
| 528 |
use the ``content_subtype`` attribute on the |
| 529 |
:class:`~django.core.mail.EmailMessage` class to change the main content type. |
| 530 |
The major type will always be ``"text"``, but you can change the |
| 531 |
subtype. For example:: |
| 532 |
|
| 533 |
msg = EmailMessage(subject, html_content, from_email, [to]) |
| 534 |
msg.content_subtype = "html" # Main content is now text/html |
| 535 |
msg.send() |
| 536 |
|
| 537 |
.. _topic-email-backends: |
| 538 |
|
| 539 |
Email backends |
| 540 |
============== |
| 541 |
|
| 542 |
The actual sending of an email is handled by the email backend. |
| 543 |
|
| 544 |
The email backend class has the following methods: |
| 545 |
|
| 546 |
* ``open()`` instantiates a long-lived email-sending connection. |
| 547 |
|
| 548 |
* ``close()`` closes the current email-sending connection. |
| 549 |
|
| 550 |
* ``send_messages(email_messages)`` sends a list of |
| 551 |
:class:`~django.core.mail.EmailMessage` objects. If the connection is |
| 552 |
not open, this call will implicitly open the connection, and close the |
| 553 |
connection afterward. If the connection is already open, it will be |
| 554 |
left open after mail has been sent. |
| 555 |
|
| 556 |
It can also be used as a context manager, which will automatically call |
| 557 |
``open()`` and ``close()`` as needed:: |
| 558 |
|
| 559 |
from django.core import mail |
| 560 |
|
| 561 |
with mail.get_connection() as connection: |
| 562 |
mail.EmailMessage( |
| 563 |
subject1, |
| 564 |
body1, |
| 565 |
from1, |
| 566 |
[to1], |
| 567 |
connection=connection, |
| 568 |
).send() |
| 569 |
mail.EmailMessage( |
| 570 |
subject2, |
| 571 |
body2, |
| 572 |
from2, |
| 573 |
[to2], |
| 574 |
connection=connection, |
| 575 |
).send() |
| 576 |
|
| 577 |
Obtaining an instance of an email backend |
| 578 |
----------------------------------------- |
| 579 |
|
| 580 |
The :func:`get_connection` function in ``django.core.mail`` returns an |
| 581 |
instance of the email backend that you can use. |
| 582 |
|
| 583 |
.. currentmodule:: django.core.mail |
| 584 |
|
| 585 |
.. function:: get_connection(backend=None, fail_silently=False, **kwargs) |
| 586 |
|
| 587 |
By default, a call to ``get_connection()`` will return an instance of the |
| 588 |
email backend specified in :setting:`EMAIL_BACKEND`. If you specify the |
| 589 |
``backend`` argument, an instance of that backend will be instantiated. |
| 590 |
|
| 591 |
The ``fail_silently`` argument controls how the backend should handle errors. |
| 592 |
If ``fail_silently`` is True, exceptions during the email sending process |
| 593 |
will be silently ignored. |
| 594 |
|
| 595 |
All other keyword arguments are passed directly to the constructor of the |
| 596 |
email backend. |
| 597 |
|
| 598 |
Django ships with several email sending backends. With the exception of the |
| 599 |
SMTP backend (which is the default), these backends are only useful during |
| 600 |
testing and development. If you have special email sending requirements, you |
| 601 |
can :ref:`write your own email backend <topic-custom-email-backend>`. |
| 602 |
|
| 603 |
.. _topic-email-smtp-backend: |
| 604 |
|
| 605 |
SMTP backend |
| 606 |
~~~~~~~~~~~~ |
| 607 |
|
| 608 |
.. class:: backends.smtp.EmailBackend(host=None, port=None, username=None, password=None, use_tls=None, fail_silently=False, use_ssl=None, timeout=None, ssl_keyfile=None, ssl_certfile=None, **kwargs) |
| 609 |
|
| 610 |
This is the default backend. Email will be sent through a SMTP server. |
| 611 |
|
| 612 |
The value for each argument is retrieved from the matching setting if the |
| 613 |
argument is ``None``: |
| 614 |
|
| 615 |
* ``host``: :setting:`EMAIL_HOST` |
| 616 |
* ``port``: :setting:`EMAIL_PORT` |
| 617 |
* ``username``: :setting:`EMAIL_HOST_USER` |
| 618 |
* ``password``: :setting:`EMAIL_HOST_PASSWORD` |
| 619 |
* ``use_tls``: :setting:`EMAIL_USE_TLS` |
| 620 |
* ``use_ssl``: :setting:`EMAIL_USE_SSL` |
| 621 |
* ``timeout``: :setting:`EMAIL_TIMEOUT` |
| 622 |
* ``ssl_keyfile``: :setting:`EMAIL_SSL_KEYFILE` |
| 623 |
* ``ssl_certfile``: :setting:`EMAIL_SSL_CERTFILE` |
| 624 |
|
| 625 |
The SMTP backend is the default configuration inherited by Django. If you |
| 626 |
want to specify it explicitly, put the following in your settings:: |
| 627 |
|
| 628 |
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" |
| 629 |
|
| 630 |
If unspecified, the default ``timeout`` will be the one provided by |
| 631 |
:func:`socket.getdefaulttimeout()`, which defaults to ``None`` (no timeout). |
| 632 |
|
| 633 |
.. _topic-email-console-backend: |
| 634 |
|
| 635 |
Console backend |
| 636 |
~~~~~~~~~~~~~~~ |
| 637 |
|
| 638 |
Instead of sending out real emails the console backend just writes the |
| 639 |
emails that would be sent to the standard output. By default, the console |
| 640 |
backend writes to ``stdout``. You can use a different stream-like object by |
| 641 |
providing the ``stream`` keyword argument when constructing the connection. |
| 642 |
|
| 643 |
To specify this backend, put the following in your settings:: |
| 644 |
|
| 645 |
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" |
| 646 |
|
| 647 |
This backend is not intended for use in production -- it is provided as a |
| 648 |
convenience that can be used during development. |
| 649 |
|
| 650 |
.. _topic-email-file-backend: |
| 651 |
|
| 652 |
File backend |
| 653 |
~~~~~~~~~~~~ |
| 654 |
|
| 655 |
The file backend writes emails to a file. A new file is created for each new |
| 656 |
session that is opened on this backend. The directory to which the files are |
| 657 |
written is either taken from the :setting:`EMAIL_FILE_PATH` setting or from |
| 658 |
the ``file_path`` keyword when creating a connection with |
| 659 |
:func:`~django.core.mail.get_connection`. |
| 660 |
|
| 661 |
To specify this backend, put the following in your settings:: |
| 662 |
|
| 663 |
EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend" |
| 664 |
EMAIL_FILE_PATH = "/tmp/app-messages" # change this to a proper location |
| 665 |
|
| 666 |
This backend is not intended for use in production -- it is provided as a |
| 667 |
convenience that can be used during development. |
| 668 |
|
| 669 |
.. _topic-email-memory-backend: |
| 670 |
|
| 671 |
In-memory backend |
| 672 |
~~~~~~~~~~~~~~~~~ |
| 673 |
|
| 674 |
The ``'locmem'`` backend stores messages in a special attribute of the |
| 675 |
``django.core.mail`` module. The ``outbox`` attribute is created when the |
| 676 |
first message is sent. It's a list with an |
| 677 |
:class:`~django.core.mail.EmailMessage` instance for each message that would |
| 678 |
be sent. |
| 679 |
|
| 680 |
To specify this backend, put the following in your settings:: |
| 681 |
|
| 682 |
EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend" |
| 683 |
|
| 684 |
This backend is not intended for use in production -- it is provided as a |
| 685 |
convenience that can be used during development and testing. |
| 686 |
|
| 687 |
Django's test runner :ref:`automatically uses this backend for testing |
| 688 |
<topics-testing-email>`. |
| 689 |
|
| 690 |
.. _topic-email-dummy-backend: |
| 691 |
|
| 692 |
Dummy backend |
| 693 |
~~~~~~~~~~~~~ |
| 694 |
|
| 695 |
As the name suggests the dummy backend does nothing with your messages. To |
| 696 |
specify this backend, put the following in your settings:: |
| 697 |
|
| 698 |
EMAIL_BACKEND = "django.core.mail.backends.dummy.EmailBackend" |
| 699 |
|
| 700 |
This backend is not intended for use in production -- it is provided as a |
| 701 |
convenience that can be used during development. |
| 702 |
|
| 703 |
.. _topic-custom-email-backend: |
| 704 |
|
| 705 |
Defining a custom email backend |
| 706 |
------------------------------- |
| 707 |
|
| 708 |
If you need to change how emails are sent you can write your own email |
| 709 |
backend. The :setting:`EMAIL_BACKEND` setting in your settings file is then |
| 710 |
the Python import path for your backend class. |
| 711 |
|
| 712 |
Custom email backends should subclass ``BaseEmailBackend`` that is located in |
| 713 |
the ``django.core.mail.backends.base`` module. A custom email backend must |
| 714 |
implement the ``send_messages(email_messages)`` method. This method receives a |
| 715 |
list of :class:`~django.core.mail.EmailMessage` instances and returns the |
| 716 |
number of successfully delivered messages. If your backend has any concept of |
| 717 |
a persistent session or connection, you should also implement the ``open()`` |
| 718 |
and ``close()`` methods. Refer to ``smtp.EmailBackend`` for a reference |
| 719 |
implementation. |
| 720 |
|
| 721 |
.. _topics-sending-multiple-emails: |
| 722 |
|
| 723 |
Sending multiple emails |
| 724 |
----------------------- |
| 725 |
|
| 726 |
Establishing and closing an SMTP connection (or any other network connection, |
| 727 |
for that matter) is an expensive process. If you have a lot of emails to send, |
| 728 |
it makes sense to reuse an SMTP connection, rather than creating and |
| 729 |
destroying a connection every time you want to send an email. |
| 730 |
|
| 731 |
There are two ways you tell an email backend to reuse a connection. |
| 732 |
|
| 733 |
Firstly, you can use the ``send_messages()`` method on a connection. This takes |
| 734 |
a list of :class:`EmailMessage` (or subclass) instances, and sends them all |
| 735 |
using that single connection. As a consequence, any :class:`connection |
| 736 |
<EmailMessage>` set on an individual message is ignored. |
| 737 |
|
| 738 |
For example, if you have a function called ``get_notification_email()`` that |
| 739 |
returns a list of :class:`~django.core.mail.EmailMessage` objects representing |
| 740 |
some periodic email you wish to send out, you could send these emails using |
| 741 |
a single call to send_messages:: |
| 742 |
|
| 743 |
from django.core import mail |
| 744 |
|
| 745 |
connection = mail.get_connection() # Use default email connection |
| 746 |
messages = get_notification_email() |
| 747 |
connection.send_messages(messages) |
| 748 |
|
| 749 |
In this example, the call to ``send_messages()`` opens a connection on the |
| 750 |
backend, sends the list of messages, and then closes the connection again. |
| 751 |
|
| 752 |
The second approach is to use the ``open()`` and ``close()`` methods on the |
| 753 |
email backend to manually control the connection. ``send_messages()`` will not |
| 754 |
manually open or close the connection if it is already open, so if you |
| 755 |
manually open the connection, you can control when it is closed. For example:: |
| 756 |
|
| 757 |
from django.core import mail |
| 758 |
|
| 759 |
connection = mail.get_connection() |
| 760 |
|
| 761 |
# Manually open the connection |
| 762 |
connection.open() |
| 763 |
|
| 764 |
# Construct an email message that uses the connection |
| 765 |
email1 = mail.EmailMessage( |
| 766 |
"Hello", |
| 767 |
"Body goes here", |
| 768 |
"[email protected]", |
| 769 |
["[email protected]"], |
| 770 |
connection=connection, |
| 771 |
) |
| 772 |
email1.send() # Send the email |
| 773 |
|
| 774 |
# Construct two more messages |
| 775 |
email2 = mail.EmailMessage( |
| 776 |
"Hello", |
| 777 |
"Body goes here", |
| 778 |
"[email protected]", |
| 779 |
["[email protected]"], |
| 780 |
) |
| 781 |
email3 = mail.EmailMessage( |
| 782 |
"Hello", |
| 783 |
"Body goes here", |
| 784 |
"[email protected]", |
| 785 |
["[email protected]"], |
| 786 |
) |
| 787 |
|
| 788 |
# Send the two emails in a single call - |
| 789 |
connection.send_messages([email2, email3]) |
| 790 |
# The connection was already open so send_messages() doesn't close it. |
| 791 |
# We need to manually close the connection. |
| 792 |
connection.close() |
| 793 |
|
| 794 |
|
| 795 |
Configuring email for development |
| 796 |
================================= |
| 797 |
|
| 798 |
There are times when you do not want Django to send emails at |
| 799 |
all. For example, while developing a website, you probably don't want |
| 800 |
to send out thousands of emails -- but you may want to validate that |
| 801 |
emails will be sent to the right people under the right conditions, |
| 802 |
and that those emails will contain the correct content. |
| 803 |
|
| 804 |
The easiest way to configure email for local development is to use the |
| 805 |
:ref:`console <topic-email-console-backend>` email backend. This backend |
| 806 |
redirects all email to ``stdout``, allowing you to inspect the content of mail. |
| 807 |
|
| 808 |
The :ref:`file <topic-email-file-backend>` email backend can also be useful |
| 809 |
during development -- this backend dumps the contents of every SMTP connection |
| 810 |
to a file that can be inspected at your leisure. |
| 811 |
|
| 812 |
Another approach is to use a "dumb" SMTP server that receives the emails |
| 813 |
locally and displays them to the terminal, but does not actually send |
| 814 |
anything. The :pypi:`aiosmtpd` package provides a way to accomplish this: |
| 815 |
|
| 816 |
.. code-block:: shell |
| 817 |
|
| 818 |
python -m pip install aiosmtpd |
| 819 |
|
| 820 |
python -m aiosmtpd -n -l localhost:8025 |
| 821 |
|
| 822 |
This command will start a minimal SMTP server listening on port 8025 of |
| 823 |
localhost. This server prints to standard output all email headers and the |
| 824 |
email body. You then only need to set the :setting:`EMAIL_HOST` and |
| 825 |
:setting:`EMAIL_PORT` accordingly. For a more detailed discussion of SMTP |
| 826 |
server options, see the documentation of the `aiosmtpd`_ module. |
| 827 |
|
| 828 |
.. _aiosmtpd: https://aiosmtpd.readthedocs.io/en/latest/ |
| 829 |
|
| 830 |
For information about unit-testing the sending of emails in your application, |
| 831 |
see the :ref:`topics-testing-email` section of the testing documentation. |