Django

Code

root/django/branches/boulder-oracle-sprint/docs/email.txt

Revision 5157, 10.1 kB (checked in by bouldersprinters, 2 years ago)

boulder-oracle-sprint: Merged to [5156]

Line 
1 ==============
2 Sending e-mail
3 ==============
4
5 Although Python makes sending e-mail relatively easy via the `smtplib library`_,
6 Django provides a couple of light wrappers over it, to make sending e-mail
7 extra quick.
8
9 The code lives in a single module: ``django.core.mail``.
10
11 .. _smtplib library: http://www.python.org/doc/current/lib/module-smtplib.html
12
13 Quick example
14 =============
15
16 In two lines::
17
18     from django.core.mail import send_mail
19
20     send_mail('Subject here', 'Here is the message.', 'from@example.com',
21         ['to@example.com'], fail_silently=False)
22
23 Mail is sent using the SMTP host and port specified in the `EMAIL_HOST`_ and
24 `EMAIL_PORT`_ settings. The `EMAIL_HOST_USER`_ and `EMAIL_HOST_PASSWORD`_
25 settings, if set, are used to authenticate to the SMTP server, and the
26 `EMAIL_USE_TLS`_ setting controls whether a secure connection is used.
27
28 .. note::
29
30     The character set of e-mail sent with ``django.core.mail`` will be set to
31     the value of your `DEFAULT_CHARSET setting`_.
32
33 .. _DEFAULT_CHARSET setting: ../settings/#default-charset
34 .. _EMAIL_HOST: ../settings/#email-host
35 .. _EMAIL_PORT: ../settings/#email-port
36 .. _EMAIL_HOST_USER: ../settings/#email-host-user
37 .. _EMAIL_HOST_PASSWORD: ../settings/#email-host-password
38 .. _EMAIL_USE_TLS: ../settings/#email-use-tls
39
40 send_mail()
41 ===========
42
43 The simplest way to send e-mail is using the function
44 ``django.core.mail.send_mail()``. Here's its definition::
45
46     send_mail(subject, message, from_email, recipient_list,
47         fail_silently=False, auth_user=None,
48         auth_password=None)
49
50 The ``subject``, ``message``, ``from_email`` and ``recipient_list`` parameters
51 are required.
52
53     * ``subject``: A string.
54     * ``message``: A string.
55     * ``from_email``: A string.
56     * ``recipient_list``: A list of strings, each an e-mail address. Each
57       member of ``recipient_list`` will see the other recipients in the "To:"
58       field of the e-mail message.
59     * ``fail_silently``: A boolean. If it's ``False``, ``send_mail`` will raise
60       an ``smtplib.SMTPException``. See the `smtplib docs`_ for a list of
61       possible exceptions, all of which are subclasses of ``SMTPException``.
62     * ``auth_user``: The optional username to use to authenticate to the SMTP
63       server. If this isn't provided, Django will use the value of the
64       ``EMAIL_HOST_USER`` setting.
65     * ``auth_password``: The optional password to use to authenticate to the
66       SMTP server. If this isn't provided, Django will use the value of the
67       ``EMAIL_HOST_PASSWORD`` setting.
68
69 .. _smtplib docs: http://www.python.org/doc/current/lib/module-smtplib.html
70
71 send_mass_mail()
72 ================
73
74 ``django.core.mail.send_mass_mail()`` is intended to handle mass e-mailing.
75 Here's the definition::
76
77     send_mass_mail(datatuple, fail_silently=False,
78         auth_user=None, auth_password=None):
79
80 ``datatuple`` is a tuple in which each element is in this format::
81
82     (subject, message, from_email, recipient_list)
83
84 ``fail_silently``, ``auth_user`` and ``auth_password`` have the same functions
85 as in ``send_mail()``.
86
87 Each separate element of ``datatuple`` results in a separate e-mail message.
88 As in ``send_mail()``, recipients in the same ``recipient_list`` will all see
89 the other addresses in the e-mail messages's "To:" field.
90
91 send_mass_mail() vs. send_mail()
92 --------------------------------
93
94 The main difference between ``send_mass_mail()`` and ``send_mail()`` is that
95 ``send_mail()`` opens a connection to the mail server each time it's executed,
96 while ``send_mass_mail()`` uses a single connection for all of its messages.
97 This makes ``send_mass_mail()`` slightly more efficient.
98
99 mail_admins()
100 =============
101
102 ``django.core.mail.mail_admins()`` is a shortcut for sending an e-mail to the
103 site admins, as defined in the `ADMINS setting`_. Here's the definition::
104
105     mail_admins(subject, message, fail_silently=False)
106
107 ``mail_admins()`` prefixes the subject with the value of the
108 `EMAIL_SUBJECT_PREFIX setting`_, which is ``"[Django] "`` by default.
109
110 The "From:" header of the e-mail will be the value of the `SERVER_EMAIL setting`_.
111
112 This method exists for convenience and readability.
113
114 .. _ADMINS setting: ../settings/#admins
115 .. _EMAIL_SUBJECT_PREFIX setting: ../settings/#email-subject-prefix
116 .. _SERVER_EMAIL setting: ../settings/#server-email
117
118 mail_managers() function
119 ========================
120
121 ``django.core.mail.mail_managers()`` is just like ``mail_admins()``, except it
122 sends an e-mail to the site managers, as defined in the `MANAGERS setting`_.
123 Here's the definition::
124
125     mail_managers(subject, message, fail_silently=False)
126
127 .. _MANAGERS setting: ../settings/#managers
128
129 Examples
130 ========
131
132 This sends a single e-mail to john@example.com and jane@example.com, with them
133 both appearing in the "To:"::
134
135     send_mail('Subject', 'Message.', 'from@example.com',
136         ['john@example.com', 'jane@example.com'])
137
138 This sends a message to john@example.com and jane@example.com, with them both
139 receiving a separate e-mail::
140
141     datatuple = (
142         ('Subject', 'Message.', 'from@example.com', ['john@example.com']),
143         ('Subject', 'Message.', 'from@example.com', ['jane@example.com']),
144     )
145     send_mass_mail(datatuple)
146
147 Preventing header injection
148 ===========================
149
150 `Header injection`_ is a security exploit in which an attacker inserts extra
151 e-mail headers to control the "To:" and "From:" in e-mail messages that your
152 scripts generate.
153
154 The Django e-mail functions outlined above all protect against header injection
155 by forbidding newlines in header values. If any ``subject``, ``from_email`` or
156 ``recipient_list`` contains a newline (in either Unix, Windows or Mac style),
157 the e-mail function (e.g. ``send_mail()``) will raise
158 ``django.core.mail.BadHeaderError`` (a subclass of ``ValueError``) and, hence,
159 will not send the e-mail. It's your responsibility to validate all data before
160 passing it to the e-mail functions.
161
162 If a ``message`` contains headers at the start of the string, the headers will
163 simply be printed as the first bit of the e-mail message.
164
165 Here's an example view that takes a ``subject``, ``message`` and ``from_email``
166 from the request's POST data, sends that to admin@example.com and redirects to
167 "/contact/thanks/" when it's done::
168
169     from django.core.mail import send_mail, BadHeaderError
170
171     def send_email(request):
172         subject = request.POST.get('subject', '')
173         message = request.POST.get('message', '')
174         from_email = request.POST.get('from_email', '')
175         if subject and message and from_email:
176             try:
177                 send_mail(subject, message, from_email, ['admin@example.com'])
178             except BadHeaderError:
179                 return HttpResponse('Invalid header found.')
180             return HttpResponseRedirect('/contact/thanks/')
181         else:
182             # In reality we'd use a manipulator
183             # to get proper validation errors.
184             return HttpResponse('Make sure all fields are entered and valid.')
185
186 .. _Header injection: http://securephp.damonkohler.com/index.php/Email_Injection
187
188 The EmailMessage and SMTPConnection classes
189 ===========================================
190
191 **New in Django development version**
192
193 Django's ``send_mail()`` and ``send_mass_mail()`` functions are actually thin
194 wrappers that make use of the ``EmailMessage`` and ``SMTPConnection`` classes
195 in ``django.core.mail``.  If you ever need to customize the way Django sends
196 e-mail, you can subclass these two classes to suit your needs.
197
198 .. note::
199     Not all features of the ``EmailMessage`` class are available through the
200     ``send_mail()`` and related wrapper functions. If you wish to use advanced
201     features, such as BCC'ed recipients or multi-part e-mail, you'll need to
202     create ``EmailMessage`` instances directly.
203
204 In general, ``EmailMessage`` is responsible for creating the e-mail message
205 itself. ``SMTPConnection`` is responsible for the network connection side of
206 the operation. This means you can reuse the same connection (an
207 ``SMTPConnection`` instance) for multiple messages.
208
209 The ``EmailMessage`` class is initialized as follows::
210
211     email = EmailMessage(subject, body, from_email, to, bcc, connection)
212
213 All of these parameters are optional. If ``from_email`` is omitted, the value
214 from ``settings.DEFAULT_FROM_EMAIL`` is used. Both the ``to`` and ``bcc``
215 parameters are lists of addresses, as strings.
216
217 For example::
218
219     email = EmailMessage('Hello', 'Body goes here', 'from@example.com',
220                 ['to1@example.com', 'to2@example.com'],
221                 ['bcc@example.com'])
222
223 The class has the following methods:
224
225     * ``send()`` sends the message, using either the connection that is
226       specified in the ``connection`` attribute, or creating a new connection
227       if none already exists.
228
229     * ``message()`` constructs a ``django.core.mail.SafeMIMEText`` object (a
230       sub-class of Python's ``email.MIMEText.MIMEText`` class) holding the
231       message to be sent. If you ever need to extend the `EmailMessage` class,
232       you'll probably want to override this method to put the content you wish
233       into the MIME object.
234
235     * ``recipients()`` returns a list of all the recipients of the message,
236       whether they're recorded in the ``to`` or ``bcc`` attributes. This is
237       another method you might need to override when sub-classing, because the
238       SMTP server needs to be told the full list of recipients when the message
239       is sent. If you add another way to specify recipients in your class, they
240       need to be returned from this method as well.
241
242 The ``SMTPConnection`` class is initialized with the host, port, username and
243 password for the SMTP server. If you don't specify one or more of those
244 options, they are read from your settings file.
245
246 If you're sending lots of messages at once, the ``send_messages()`` method of
247 the ``SMTPConnection`` class is useful. It takes a list of ``EmailMessage``
248 instances (or subclasses) and sends them over a single connection. For example,
249 if you have a function called ``get_notification_email()`` that returns a
250 list of ``EmailMessage`` objects representing some periodic e-mail you wish to
251 send out, you could send this with::
252
253     connection = SMTPConnection()   # Use default settings for connection
254     messages = get_notification_email()
255     connection.send_messages(messages)
Note: See TracBrowser for help on using the browser.