email.txt 26 KB

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