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