email.txt 30 KB

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