5 .. module:: django.core.mail
6 :synopsis: Helpers to easily send email.
8 Although Python makes sending email relatively easy via the :mod:`smtplib`
9 module, Django provides a couple of light wrappers over it. These wrappers are
10 provided to make sending email extra quick, to make it easy to test email
11 sending during development, and to provide support for platforms that can't use
14 The code lives in the ``django.core.mail`` module.
21 from django.core.mail import send_mail
23 send_mail('Subject here', 'Here is the message.', 'from@example.com',
24 ['to@example.com'], fail_silently=False)
26 Mail is sent using the SMTP host and port specified in the
27 :setting:`EMAIL_HOST` and :setting:`EMAIL_PORT` settings. The
28 :setting:`EMAIL_HOST_USER` and :setting:`EMAIL_HOST_PASSWORD` settings, if
29 set, are used to authenticate to the SMTP server, and the
30 :setting:`EMAIL_USE_TLS` setting controls whether a secure connection is used.
34 The character set of email sent with ``django.core.mail`` will be set to
35 the value of your :setting:`DEFAULT_CHARSET` setting.
40 .. function:: send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None)
42 The simplest way to send email is using
43 ``django.core.mail.send_mail()``.
45 The ``subject``, ``message``, ``from_email`` and ``recipient_list`` parameters
48 * ``subject``: A string.
49 * ``message``: A string.
50 * ``from_email``: A string.
51 * ``recipient_list``: A list of strings, each an email address. Each
52 member of ``recipient_list`` will see the other recipients in the "To:"
53 field of the email message.
54 * ``fail_silently``: A boolean. If it's ``False``, ``send_mail`` will raise
55 an :exc:`smtplib.SMTPException`. See the :mod:`smtplib` docs for a list of
56 possible exceptions, all of which are subclasses of
57 :exc:`~smtplib.SMTPException`.
58 * ``auth_user``: The optional username to use to authenticate to the SMTP
59 server. If this isn't provided, Django will use the value of the
60 :setting:`EMAIL_HOST_USER` setting.
61 * ``auth_password``: The optional password to use to authenticate to the
62 SMTP server. If this isn't provided, Django will use the value of the
63 :setting:`EMAIL_HOST_PASSWORD` setting.
64 * ``connection``: The optional email backend to use to send the mail.
65 If unspecified, an instance of the default backend will be used.
66 See the documentation on :ref:`Email backends <topic-email-backends>`
72 .. function:: send_mass_mail(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None)
74 ``django.core.mail.send_mass_mail()`` is intended to handle mass emailing.
76 ``datatuple`` is a tuple in which each element is in this format::
78 (subject, message, from_email, recipient_list)
80 ``fail_silently``, ``auth_user`` and ``auth_password`` have the same functions
81 as in :meth:`~django.core.mail.send_mail()`.
83 Each separate element of ``datatuple`` results in a separate email message.
84 As in :meth:`~django.core.mail.send_mail()`, recipients in the same
85 ``recipient_list`` will all see the other addresses in the email messages'
88 For example, the following code would send two different messages to
89 two different sets of recipients; however, only one connection to the
90 mail server would be opened::
92 message1 = ('Subject here', 'Here is the message', 'from@example.com', ['first@example.com', 'other@example.com'])
93 message2 = ('Another Subject', 'Here is another message', 'from@example.com', ['second@test.com'])
94 send_mass_mail((message1, message2), fail_silently=False)
96 send_mass_mail() vs. send_mail()
97 --------------------------------
99 The main difference between :meth:`~django.core.mail.send_mass_mail()` and
100 :meth:`~django.core.mail.send_mail()` is that
101 :meth:`~django.core.mail.send_mail()` opens a connection to the mail server
102 each time it's executed, while :meth:`~django.core.mail.send_mass_mail()` uses
103 a single connection for all of its messages. This makes
104 :meth:`~django.core.mail.send_mass_mail()` slightly more efficient.
109 .. function:: mail_admins(subject, message, fail_silently=False, connection=None, html_message=None)
111 ``django.core.mail.mail_admins()`` is a shortcut for sending an email to the
112 site admins, as defined in the :setting:`ADMINS` setting.
114 ``mail_admins()`` prefixes the subject with the value of the
115 :setting:`EMAIL_SUBJECT_PREFIX` setting, which is ``"[Django] "`` by default.
117 The "From:" header of the email will be the value of the
118 :setting:`SERVER_EMAIL` setting.
120 This method exists for convenience and readability.
122 .. versionchanged:: 1.3
124 If ``html_message`` is provided, the resulting email will be a
125 :mimetype:`multipart/alternative` email with ``message`` as the
126 :mimetype:`text/plain` content type and ``html_message`` as the
127 :mimetype:`text/html` content type.
132 .. function:: mail_managers(subject, message, fail_silently=False, connection=None, html_message=None)
134 ``django.core.mail.mail_managers()`` is just like ``mail_admins()``, except it
135 sends an email to the site managers, as defined in the :setting:`MANAGERS`
141 This sends a single email to john@example.com and jane@example.com, with them
142 both appearing in the "To:"::
144 send_mail('Subject', 'Message.', 'from@example.com',
145 ['john@example.com', 'jane@example.com'])
147 This sends a message to john@example.com and jane@example.com, with them both
148 receiving a separate email::
151 ('Subject', 'Message.', 'from@example.com', ['john@example.com']),
152 ('Subject', 'Message.', 'from@example.com', ['jane@example.com']),
154 send_mass_mail(datatuple)
156 Preventing header injection
157 ===========================
159 `Header injection`_ is a security exploit in which an attacker inserts extra
160 email headers to control the "To:" and "From:" in email messages that your
163 The Django email functions outlined above all protect against header injection
164 by forbidding newlines in header values. If any ``subject``, ``from_email`` or
165 ``recipient_list`` contains a newline (in either Unix, Windows or Mac style),
166 the email function (e.g. :meth:`~django.core.mail.send_mail()`) will raise
167 ``django.core.mail.BadHeaderError`` (a subclass of ``ValueError``) and, hence,
168 will not send the email. It's your responsibility to validate all data before
169 passing it to the email functions.
171 If a ``message`` contains headers at the start of the string, the headers will
172 simply be printed as the first bit of the email message.
174 Here's an example view that takes a ``subject``, ``message`` and ``from_email``
175 from the request's POST data, sends that to admin@example.com and redirects to
176 "/contact/thanks/" when it's done::
178 from django.core.mail import send_mail, BadHeaderError
180 def send_email(request):
181 subject = request.POST.get('subject', '')
182 message = request.POST.get('message', '')
183 from_email = request.POST.get('from_email', '')
184 if subject and message and from_email:
186 send_mail(subject, message, from_email, ['admin@example.com'])
187 except BadHeaderError:
188 return HttpResponse('Invalid header found.')
189 return HttpResponseRedirect('/contact/thanks/')
191 # In reality we'd use a form class
192 # to get proper validation errors.
193 return HttpResponse('Make sure all fields are entered and valid.')
195 .. _Header injection: http://www.nyphp.org/phundamentals/8_Preventing-Email-Header-Injection
197 .. _emailmessage-and-smtpconnection:
199 The EmailMessage class
200 ======================
202 Django's :meth:`~django.core.mail.send_mail()` and
203 :meth:`~django.core.mail.send_mass_mail()` functions are actually thin
204 wrappers that make use of the :class:`~django.core.mail.EmailMessage` class.
206 Not all features of the :class:`~django.core.mail.EmailMessage` class are
207 available through the :meth:`~django.core.mail.send_mail()` and related
208 wrapper functions. If you wish to use advanced features, such as BCC'ed
209 recipients, file attachments, or multi-part email, you'll need to create
210 :class:`~django.core.mail.EmailMessage` instances directly.
213 This is a design feature. :meth:`~django.core.mail.send_mail()` and
214 related functions were originally the only interface Django provided.
215 However, the list of parameters they accepted was slowly growing over
216 time. It made sense to move to a more object-oriented design for email
217 messages and retain the original functions only for backwards
220 :class:`~django.core.mail.EmailMessage` is responsible for creating the email
221 message itself. The :ref:`email backend <topic-email-backends>` is then
222 responsible for sending the email.
224 For convenience, :class:`~django.core.mail.EmailMessage` provides a simple
225 ``send()`` method for sending a single email. If you need to send multiple
226 messages, the email backend API :ref:`provides an alternative
227 <topics-sending-multiple-emails>`.
232 .. class:: EmailMessage
234 The :class:`~django.core.mail.EmailMessage` class is initialized with the
235 following parameters (in the given order, if positional arguments are used).
236 All parameters are optional and can be set at any time prior to calling the
239 .. versionchanged:: 1.3
240 The ``cc`` argument was added.
242 * ``subject``: The subject line of the email.
244 * ``body``: The body text. This should be a plain text message.
246 * ``from_email``: The sender's address. Both ``fred@example.com`` and
247 ``Fred <fred@example.com>`` forms are legal. If omitted, the
248 :setting:`DEFAULT_FROM_EMAIL` setting is used.
250 * ``to``: A list or tuple of recipient addresses.
252 * ``bcc``: A list or tuple of addresses used in the "Bcc" header when
255 * ``connection``: An email backend instance. Use this parameter if
256 you want to use the same connection for multiple messages. If omitted, a
257 new connection is created when ``send()`` is called.
259 * ``attachments``: A list of attachments to put on the message. These can
260 be either ``email.MIMEBase.MIMEBase`` instances, or ``(filename,
261 content, mimetype)`` triples.
263 * ``headers``: A dictionary of extra headers to put on the message. The
264 keys are the header name, values are the header values. It's up to the
265 caller to ensure header names and values are in the correct format for
268 * ``cc``: A list or tuple of recipient addresses used in the "Cc" header
269 when sending the email.
273 email = EmailMessage('Hello', 'Body goes here', 'from@example.com',
274 ['to1@example.com', 'to2@example.com'], ['bcc@example.com'],
275 headers = {'Reply-To': 'another@example.com'})
277 The class has the following methods:
279 * ``send(fail_silently=False)`` sends the message. If a connection was
280 specified when the email was constructed, that connection will be used.
281 Otherwise, an instance of the default backend will be instantiated and
282 used. If the keyword argument ``fail_silently`` is ``True``, exceptions
283 raised while sending the message will be quashed.
285 * ``message()`` constructs a ``django.core.mail.SafeMIMEText`` object (a
286 subclass of Python's ``email.MIMEText.MIMEText`` class) or a
287 ``django.core.mail.SafeMIMEMultipart`` object holding the message to be
288 sent. If you ever need to extend the
289 :class:`~django.core.mail.EmailMessage` class, you'll probably want to
290 override this method to put the content you want into the MIME object.
292 * ``recipients()`` returns a list of all the recipients of the message,
293 whether they're recorded in the ``to``, ``cc`` or ``bcc`` attributes. This
294 is another method you might need to override when subclassing, because the
295 SMTP server needs to be told the full list of recipients when the message
296 is sent. If you add another way to specify recipients in your class, they
297 need to be returned from this method as well.
299 * ``attach()`` creates a new file attachment and adds it to the message.
300 There are two ways to call ``attach()``:
302 * You can pass it a single argument that is an
303 ``email.MIMEBase.MIMEBase`` instance. This will be inserted directly
304 into the resulting message.
306 * Alternatively, you can pass ``attach()`` three arguments:
307 ``filename``, ``content`` and ``mimetype``. ``filename`` is the name
308 of the file attachment as it will appear in the email, ``content`` is
309 the data that will be contained inside the attachment and
310 ``mimetype`` is the optional MIME type for the attachment. If you
311 omit ``mimetype``, the MIME content type will be guessed from the
312 filename of the attachment.
316 message.attach('design.png', img_data, 'image/png')
318 * ``attach_file()`` creates a new attachment using a file from your
319 filesystem. Call it with the path of the file to attach and, optionally,
320 the MIME type to use for the attachment. If the MIME type is omitted, it
321 will be guessed from the filename. The simplest use would be::
323 message.attach_file('/images/weather_map.png')
325 .. _DEFAULT_FROM_EMAIL: ../settings/#default-from-email
327 Sending alternative content types
328 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
330 It can be useful to include multiple versions of the content in an email; the
331 classic example is to send both text and HTML versions of a message. With
332 Django's email library, you can do this using the ``EmailMultiAlternatives``
333 class. This subclass of :class:`~django.core.mail.EmailMessage` has an
334 ``attach_alternative()`` method for including extra versions of the message
335 body in the email. All the other methods (including the class initialization)
336 are inherited directly from :class:`~django.core.mail.EmailMessage`.
338 To send a text and HTML combination, you could write::
340 from django.core.mail import EmailMultiAlternatives
342 subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
343 text_content = 'This is an important message.'
344 html_content = '<p>This is an <strong>important</strong> message.</p>'
345 msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
346 msg.attach_alternative(html_content, "text/html")
349 By default, the MIME type of the ``body`` parameter in an
350 :class:`~django.core.mail.EmailMessage` is ``"text/plain"``. It is good
351 practice to leave this alone, because it guarantees that any recipient will be
352 able to read the email, regardless of their mail client. However, if you are
353 confident that your recipients can handle an alternative content type, you can
354 use the ``content_subtype`` attribute on the
355 :class:`~django.core.mail.EmailMessage` class to change the main content type.
356 The major type will always be ``"text"``, but you can change the
357 subtype. For example::
359 msg = EmailMessage(subject, html_content, from_email, [to])
360 msg.content_subtype = "html" # Main content is now text/html
363 .. _topic-email-backends:
368 .. versionadded:: 1.2
370 The actual sending of an email is handled by the email backend.
372 The email backend class has the following methods:
374 * ``open()`` instantiates an long-lived email-sending connection.
376 * ``close()`` closes the current email-sending connection.
378 * ``send_messages(email_messages)`` sends a list of
379 :class:`~django.core.mail.EmailMessage` objects. If the connection is
380 not open, this call will implicitly open the connection, and close the
381 connection afterwards. If the connection is already open, it will be
382 left open after mail has been sent.
384 Obtaining an instance of an email backend
385 -----------------------------------------
387 The :meth:`get_connection` function in ``django.core.mail`` returns an
388 instance of the email backend that you can use.
390 .. currentmodule:: django.core.mail
392 .. function:: get_connection(backend=None, fail_silently=False, *args, **kwargs)
394 By default, a call to ``get_connection()`` will return an instance of the
395 email backend specified in :setting:`EMAIL_BACKEND`. If you specify the
396 ``backend`` argument, an instance of that backend will be instantiated.
398 The ``fail_silently`` argument controls how the backend should handle errors.
399 If ``fail_silently`` is True, exceptions during the email sending process
400 will be silently ignored.
402 All other arguments are passed directly to the constructor of the
405 Django ships with several email sending backends. With the exception of the
406 SMTP backend (which is the default), these backends are only useful during
407 testing and development. If you have special email sending requirements, you
408 can :ref:`write your own email backend <topic-custom-email-backend>`.
410 .. _topic-email-smtp-backend:
415 This is the default backend. Email will be sent through a SMTP server.
416 The server address and authentication credentials are set in the
417 :setting:`EMAIL_HOST`, :setting:`EMAIL_PORT`, :setting:`EMAIL_HOST_USER`,
418 :setting:`EMAIL_HOST_PASSWORD` and :setting:`EMAIL_USE_TLS` settings in your
421 The SMTP backend is the default configuration inherited by Django. If you
422 want to specify it explicitly, put the following in your settings::
424 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
426 .. _topic-email-console-backend:
431 Instead of sending out real emails the console backend just writes the
432 emails that would be send to the standard output. By default, the console
433 backend writes to ``stdout``. You can use a different stream-like object by
434 providing the ``stream`` keyword argument when constructing the connection.
436 To specify this backend, put the following in your settings::
438 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
440 This backend is not intended for use in production -- it is provided as a
441 convenience that can be used during development.
443 .. _topic-email-file-backend:
448 The file backend writes emails to a file. A new file is created for each new
449 session that is opened on this backend. The directory to which the files are
450 written is either taken from the :setting:`EMAIL_FILE_PATH` setting or from
451 the ``file_path`` keyword when creating a connection with
452 :meth:`~django.core.mail.get_connection`.
454 To specify this backend, put the following in your settings::
456 EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
457 EMAIL_FILE_PATH = '/tmp/app-messages' # change this to a proper location
459 This backend is not intended for use in production -- it is provided as a
460 convenience that can be used during development.
462 .. _topic-email-memory-backend:
467 The ``'locmem'`` backend stores messages in a special attribute of the
468 ``django.core.mail`` module. The ``outbox`` attribute is created when the
469 first message is sent. It's a list with an
470 :class:`~django.core.mail.EmailMessage` instance for each message that would
473 To specify this backend, put the following in your settings::
475 EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
477 This backend is not intended for use in production -- it is provided as a
478 convenience that can be used during development and testing.
480 .. _topic-email-dummy-backend:
485 As the name suggests the dummy backend does nothing with your messages. To
486 specify this backend, put the following in your settings::
488 EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
490 This backend is not intended for use in production -- it is provided as a
491 convenience that can be used during development.
493 .. _topic-custom-email-backend:
495 Defining a custom email backend
496 -------------------------------
498 If you need to change how emails are sent you can write your own email
499 backend. The :setting:`EMAIL_BACKEND` setting in your settings file is then
500 the Python import path for your backend class.
502 Custom email backends should subclass ``BaseEmailBackend`` that is located in
503 the ``django.core.mail.backends.base`` module. A custom email backend must
504 implement the ``send_messages(email_messages)`` method. This method receives a
505 list of :class:`~django.core.mail.EmailMessage` instances and returns the
506 number of successfully delivered messages. If your backend has any concept of
507 a persistent session or connection, you should also implement the ``open()``
508 and ``close()`` methods. Refer to ``smtp.EmailBackend`` for a reference
511 .. _topics-sending-multiple-emails:
513 Sending multiple emails
514 -----------------------
516 Establishing and closing an SMTP connection (or any other network connection,
517 for that matter) is an expensive process. If you have a lot of emails to send,
518 it makes sense to reuse an SMTP connection, rather than creating and
519 destroying a connection every time you want to send an email.
521 There are two ways you tell an email backend to reuse a connection.
523 Firstly, you can use the ``send_messages()`` method. ``send_messages()`` takes
524 a list of :class:`~django.core.mail.EmailMessage` instances (or subclasses),
525 and sends them all using a single connection.
527 For example, if you have a function called ``get_notification_email()`` that
528 returns a list of :class:`~django.core.mail.EmailMessage` objects representing
529 some periodic email you wish to send out, you could send these emails using
530 a single call to send_messages::
532 from django.core import mail
533 connection = mail.get_connection() # Use default email connection
534 messages = get_notification_email()
535 connection.send_messages(messages)
537 In this example, the call to ``send_messages()`` opens a connection on the
538 backend, sends the list of messages, and then closes the connection again.
540 The second approach is to use the ``open()`` and ``close()`` methods on the
541 email backend to manually control the connection. ``send_messages()`` will not
542 manually open or close the connection if it is already open, so if you
543 manually open the connection, you can control when it is closed. For example::
545 from django.core import mail
546 connection = mail.get_connection()
548 # Manually open the connection
551 # Construct an email message that uses the connection
552 email1 = mail.EmailMessage('Hello', 'Body goes here', 'from@example.com',
553 ['to1@example.com'], connection=connection)
554 email1.send() # Send the email
556 # Construct two more messages
557 email2 = mail.EmailMessage('Hello', 'Body goes here', 'from@example.com',
559 email3 = mail.EmailMessage('Hello', 'Body goes here', 'from@example.com',
562 # Send the two emails in a single call -
563 connection.send_messages([email2, email3])
564 # The connection was already open so send_messages() doesn't close it.
565 # We need to manually close the connection.
569 Testing email sending
570 =====================
572 There are times when you do not want Django to send emails at
573 all. For example, while developing a Web site, you probably don't want
574 to send out thousands of emails -- but you may want to validate that
575 emails will be sent to the right people under the right conditions,
576 and that those emails will contain the correct content.
578 The easiest way to test your project's use of email is to use the ``console``
579 email backend. This backend redirects all email to stdout, allowing you to
580 inspect the content of mail.
582 The ``file`` email backend can also be useful during development -- this backend
583 dumps the contents of every SMTP connection to a file that can be inspected
586 Another approach is to use a "dumb" SMTP server that receives the emails
587 locally and displays them to the terminal, but does not actually send
588 anything. Python has a built-in way to accomplish this with a single command::
590 python -m smtpd -n -c DebuggingServer localhost:1025
592 This command will start a simple SMTP server listening on port 1025 of
593 localhost. This server simply prints to standard output all email headers and
594 the email body. You then only need to set the :setting:`EMAIL_HOST` and
595 :setting:`EMAIL_PORT` accordingly, and you are set.
597 For a more detailed discussion of testing and processing of emails locally,
598 see the Python documentation for the :mod:`smtpd` module.