email.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. .. _topics-email:
  2. ==============
  3. Sending e-mail
  4. ==============
  5. .. module:: django.core.mail
  6. :synopsis: Helpers to easily send e-mail.
  7. Although Python makes sending e-mail relatively easy via the `smtplib library`_,
  8. Django provides a couple of light wrappers over it, to make sending e-mail
  9. extra quick.
  10. The code lives in a single module: ``django.core.mail``.
  11. .. _smtplib library: http://www.python.org/doc/current/lib/module-smtplib.html
  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 :setting:`EMAIL_HOST`
  19. and :setting:`EMAIL_PORT` settings. The :setting:`EMAIL_HOST_USER` and
  20. :setting:`EMAIL_HOST_PASSWORD` settings, if set, are used to authenticate to the
  21. SMTP server, and the :setting:`EMAIL_USE_TLS` setting controls whether a secure
  22. connection is used.
  23. .. note::
  24. The character set of e-mail sent with ``django.core.mail`` will be set to
  25. the value of your :setting:`DEFAULT_CHARSET` setting.
  26. send_mail()
  27. ===========
  28. The simplest way to send e-mail is using the function
  29. ``django.core.mail.send_mail()``. Here's its definition:
  30. .. function:: send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None)
  31. The ``subject``, ``message``, ``from_email`` and ``recipient_list`` parameters
  32. are required.
  33. * ``subject``: A string.
  34. * ``message``: A string.
  35. * ``from_email``: A string.
  36. * ``recipient_list``: A list of strings, each an e-mail address. Each
  37. member of ``recipient_list`` will see the other recipients in the "To:"
  38. field of the e-mail message.
  39. * ``fail_silently``: A boolean. If it's ``False``, ``send_mail`` will raise
  40. an ``smtplib.SMTPException``. See the `smtplib docs`_ for a list of
  41. possible exceptions, all of which are subclasses of ``SMTPException``.
  42. * ``auth_user``: The optional username to use to authenticate to the SMTP
  43. server. If this isn't provided, Django will use the value of the
  44. ``EMAIL_HOST_USER`` setting.
  45. * ``auth_password``: The optional password to use to authenticate to the
  46. SMTP server. If this isn't provided, Django will use the value of the
  47. ``EMAIL_HOST_PASSWORD`` setting.
  48. .. _smtplib docs: http://www.python.org/doc/current/lib/module-smtplib.html
  49. send_mass_mail()
  50. ================
  51. ``django.core.mail.send_mass_mail()`` is intended to handle mass e-mailing.
  52. Here's the definition:
  53. .. function:: send_mass_mail(datatuple, fail_silently=False, auth_user=None, auth_password=None)
  54. ``datatuple`` is a tuple in which each element is in this format::
  55. (subject, message, from_email, recipient_list)
  56. ``fail_silently``, ``auth_user`` and ``auth_password`` have the same functions
  57. as in ``send_mail()``.
  58. Each separate element of ``datatuple`` results in a separate e-mail message.
  59. As in ``send_mail()``, recipients in the same ``recipient_list`` will all see
  60. the other addresses in the e-mail messages' "To:" field.
  61. send_mass_mail() vs. send_mail()
  62. --------------------------------
  63. The main difference between ``send_mass_mail()`` and ``send_mail()`` is that
  64. ``send_mail()`` opens a connection to the mail server each time it's executed,
  65. while ``send_mass_mail()`` uses a single connection for all of its messages.
  66. This makes ``send_mass_mail()`` slightly more efficient.
  67. mail_admins()
  68. =============
  69. ``django.core.mail.mail_admins()`` is a shortcut for sending an e-mail to the
  70. site admins, as defined in the :setting:`ADMINS` setting. Here's the definition:
  71. .. function:: mail_admins(subject, message, fail_silently=False)
  72. ``mail_admins()`` prefixes the subject with the value of the
  73. :setting:`EMAIL_SUBJECT_PREFIX` setting, which is ``"[Django] "`` by default.
  74. The "From:" header of the e-mail will be the value of the
  75. :setting:`SERVER_EMAIL` setting.
  76. This method exists for convenience and readability.
  77. mail_managers() function
  78. ========================
  79. ``django.core.mail.mail_managers()`` is just like ``mail_admins()``, except it
  80. sends an e-mail to the site managers, as defined in the :setting:`MANAGERS`
  81. setting. Here's the definition:
  82. .. function:: mail_managers(subject, message, fail_silently=False)
  83. Examples
  84. ========
  85. This sends a single e-mail to john@example.com and jane@example.com, with them
  86. both appearing in the "To:"::
  87. send_mail('Subject', 'Message.', 'from@example.com',
  88. ['john@example.com', 'jane@example.com'])
  89. This sends a message to john@example.com and jane@example.com, with them both
  90. receiving a separate e-mail::
  91. datatuple = (
  92. ('Subject', 'Message.', 'from@example.com', ['john@example.com']),
  93. ('Subject', 'Message.', 'from@example.com', ['jane@example.com']),
  94. )
  95. send_mass_mail(datatuple)
  96. Preventing header injection
  97. ===========================
  98. `Header injection`_ is a security exploit in which an attacker inserts extra
  99. e-mail headers to control the "To:" and "From:" in e-mail messages that your
  100. scripts generate.
  101. The Django e-mail functions outlined above all protect against header injection
  102. by forbidding newlines in header values. If any ``subject``, ``from_email`` or
  103. ``recipient_list`` contains a newline (in either Unix, Windows or Mac style),
  104. the e-mail function (e.g. ``send_mail()``) will raise
  105. ``django.core.mail.BadHeaderError`` (a subclass of ``ValueError``) and, hence,
  106. will not send the e-mail. It's your responsibility to validate all data before
  107. passing it to the e-mail functions.
  108. If a ``message`` contains headers at the start of the string, the headers will
  109. simply be printed as the first bit of the e-mail message.
  110. Here's an example view that takes a ``subject``, ``message`` and ``from_email``
  111. from the request's POST data, sends that to admin@example.com and redirects to
  112. "/contact/thanks/" when it's done::
  113. from django.core.mail import send_mail, BadHeaderError
  114. def send_email(request):
  115. subject = request.POST.get('subject', '')
  116. message = request.POST.get('message', '')
  117. from_email = request.POST.get('from_email', '')
  118. if subject and message and from_email:
  119. try:
  120. send_mail(subject, message, from_email, ['admin@example.com'])
  121. except BadHeaderError:
  122. return HttpResponse('Invalid header found.')
  123. return HttpResponseRedirect('/contact/thanks/')
  124. else:
  125. # In reality we'd use a form class
  126. # to get proper validation errors.
  127. return HttpResponse('Make sure all fields are entered and valid.')
  128. .. _Header injection: http://www.nyphp.org/phundamentals/email_header_injection.php
  129. .. _emailmessage-and-smtpconnection:
  130. The EmailMessage and SMTPConnection classes
  131. ===========================================
  132. .. versionadded:: 1.0
  133. Django's ``send_mail()`` and ``send_mass_mail()`` functions are actually thin
  134. wrappers that make use of the ``EmailMessage`` and ``SMTPConnection`` classes
  135. in ``django.core.mail``. If you ever need to customize the way Django sends
  136. e-mail, you can subclass these two classes to suit your needs.
  137. .. note::
  138. Not all features of the ``EmailMessage`` class are available through the
  139. ``send_mail()`` and related wrapper functions. If you wish to use advanced
  140. features, such as BCC'ed recipients, file attachments, or multi-part
  141. e-mail, you'll need to create ``EmailMessage`` instances directly.
  142. This is a design feature. ``send_mail()`` and related functions were
  143. originally the only interface Django provided. However, the list of
  144. parameters they accepted was slowly growing over time. It made sense to
  145. move to a more object-oriented design for e-mail messages and retain the
  146. original functions only for backwards compatibility.
  147. In general, ``EmailMessage`` is responsible for creating the e-mail message
  148. itself. ``SMTPConnection`` is responsible for the network connection side of
  149. the operation. This means you can reuse the same connection (an
  150. ``SMTPConnection`` instance) for multiple messages.
  151. EmailMessage Objects
  152. --------------------
  153. .. class:: EmailMessage
  154. The ``EmailMessage`` class is initialized with the following parameters (in
  155. the given order, if positional arguments are used). All parameters are
  156. optional and can be set at any time prior to calling the ``send()`` method.
  157. * ``subject``: The subject line of the e-mail.
  158. * ``body``: The body text. This should be a plain text message.
  159. * ``from_email``: The sender's address. Both ``fred@example.com`` and
  160. ``Fred <fred@example.com>`` forms are legal. If omitted, the
  161. :setting:`DEFAULT_FROM_EMAIL` setting is used.
  162. * ``to``: A list or tuple of recipient addresses.
  163. * ``bcc``: A list or tuple of addresses used in the "Bcc" header when
  164. sending the e-mail.
  165. * ``connection``: An ``SMTPConnection`` instance. Use this parameter if
  166. you want to use the same connection for multiple messages. If omitted, a
  167. new connection is created when ``send()`` is called.
  168. * ``attachments``: A list of attachments to put on the message. These can
  169. be either ``email.MIMEBase.MIMEBase`` instances, or ``(filename,
  170. content, mimetype)`` triples.
  171. * ``headers``: A dictionary of extra headers to put on the message. The
  172. keys are the header name, values are the header values. It's up to the
  173. caller to ensure header names and values are in the correct format for
  174. an e-mail message.
  175. For example::
  176. email = EmailMessage('Hello', 'Body goes here', 'from@example.com',
  177. ['to1@example.com', 'to2@example.com'], ['bcc@example.com'],
  178. headers = {'Reply-To': 'another@example.com'})
  179. The class has the following methods:
  180. * ``send(fail_silently=False)`` sends the message, using either
  181. the connection that is specified in the ``connection``
  182. attribute, or creating a new connection if none already
  183. exists. If the keyword argument ``fail_silently`` is ``True``,
  184. exceptions raised while sending the message will be quashed.
  185. * ``message()`` constructs a ``django.core.mail.SafeMIMEText`` object (a
  186. subclass of Python's ``email.MIMEText.MIMEText`` class) or a
  187. ``django.core.mail.SafeMIMEMultipart`` object holding the
  188. message to be sent. If you ever need to extend the ``EmailMessage`` class,
  189. you'll probably want to override this method to put the content you want
  190. into the MIME object.
  191. * ``recipients()`` returns a list of all the recipients of the message,
  192. whether they're recorded in the ``to`` or ``bcc`` attributes. This is
  193. another method you might need to override when subclassing, because the
  194. SMTP server needs to be told the full list of recipients when the message
  195. is sent. If you add another way to specify recipients in your class, they
  196. need to be returned from this method as well.
  197. * ``attach()`` creates a new file attachment and adds it to the message.
  198. There are two ways to call ``attach()``:
  199. * You can pass it a single argument that is an
  200. ``email.MIMEBase.MIMEBase`` instance. This will be inserted directly
  201. into the resulting message.
  202. * Alternatively, you can pass ``attach()`` three arguments:
  203. ``filename``, ``content`` and ``mimetype``. ``filename`` is the name
  204. of the file attachment as it will appear in the e-mail, ``content`` is
  205. the data that will be contained inside the attachment and
  206. ``mimetype`` is the optional MIME type for the attachment. If you
  207. omit ``mimetype``, the MIME content type will be guessed from the
  208. filename of the attachment.
  209. For example::
  210. message.attach('design.png', img_data, 'image/png')
  211. * ``attach_file()`` creates a new attachment using a file from your
  212. filesystem. Call it with the path of the file to attach and, optionally,
  213. the MIME type to use for the attachment. If the MIME type is omitted, it
  214. will be guessed from the filename. The simplest use would be::
  215. message.attach_file('/images/weather_map.png')
  216. .. _DEFAULT_FROM_EMAIL: ../settings/#default-from-email
  217. Sending alternative content types
  218. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  219. It can be useful to include multiple versions of the content in an e-mail;
  220. the classic example is to send both text and HTML versions of a message. With
  221. Django's e-mail library, you can do this using the ``EmailMultiAlternatives``
  222. class. This subclass of ``EmailMessage`` has an ``attach_alternative()`` method
  223. for including extra versions of the message body in the e-mail. All the other
  224. methods (including the class initialization) are inherited directly from
  225. ``EmailMessage``.
  226. To send a text and HTML combination, you could write::
  227. from django.core.mail import EmailMultiAlternatives
  228. subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
  229. text_content = 'This is an important message.'
  230. html_content = '<p>This is an <strong>important</strong> message.</p>'
  231. msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
  232. msg.attach_alternative(html_content, "text/html")
  233. msg.send()
  234. By default, the MIME type of the ``body`` parameter in an ``EmailMessage`` is
  235. ``"text/plain"``. It is good practice to leave this alone, because it
  236. guarantees that any recipient will be able to read the e-mail, regardless of
  237. their mail client. However, if you are confident that your recipients can
  238. handle an alternative content type, you can use the ``content_subtype``
  239. attribute on the ``EmailMessage`` class to change the main content type. The
  240. major type will always be ``"text"``, but you can change it to the subtype. For
  241. example::
  242. msg = EmailMessage(subject, html_content, from_email, [to])
  243. msg.content_subtype = "html" # Main content is now text/html
  244. msg.send()
  245. SMTPConnection Objects
  246. ----------------------
  247. .. class:: SMTPConnection
  248. The ``SMTPConnection`` class is initialized with the host, port, username and
  249. password for the SMTP server. If you don't specify one or more of those
  250. options, they are read from your settings file.
  251. If you're sending lots of messages at once, the ``send_messages()`` method of
  252. the ``SMTPConnection`` class is useful. It takes a list of ``EmailMessage``
  253. instances (or subclasses) and sends them over a single connection. For example,
  254. if you have a function called ``get_notification_email()`` that returns a
  255. list of ``EmailMessage`` objects representing some periodic e-mail you wish to
  256. send out, you could send this with::
  257. connection = SMTPConnection() # Use default settings for connection
  258. messages = get_notification_email()
  259. connection.send_messages(messages)