email.txt 27 KB

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