email.txt 31 KB

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