email.txt 25 KB

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