Django

Code

root/django/branches/unicode/docs/email.txt

Revision 5580, 14.5 kB (checked in by mtredinnick, 1 year ago)

unicode: Merged changes from trunk up to [5579].

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: ../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, file attachments, or multi-part
202     e-mail, you'll need to create ``EmailMessage`` instances directly.
203
204     This is a design feature. ``send_mail()`` and related functions were
205     originally the only interface Django provided. However, the list of
206     parameters they accepted was slowly growing over time. It made sense to
207     move to a more object-oriented design for e-mail messages and retain the
208     original functions only for backwards compatibility.
209
210 In general, ``EmailMessage`` is responsible for creating the e-mail message
211 itself. ``SMTPConnection`` is responsible for the network connection side of
212 the operation. This means you can reuse the same connection (an
213 ``SMTPConnection`` instance) for multiple messages.
214
215 E-mail messages
216 ---------------
217
218 The ``EmailMessage`` class is initialized with the following parameters (in
219 the given order, if positional arguments are used). All parameters are
220 optional and can be set at any time prior to calling the ``send()`` method.
221
222     * ``subject``: The subject line of the e-mail.
223
224     * ``body``: The body text. This should be a plain text message.
225
226     * ``from_email``: The sender's address. Both ``fred@example.com`` and
227       ``Fred <fred@example.com>`` forms are legal. If omitted, the
228       ``DEFAULT_FROM_EMAIL`` setting is used.
229
230     * ``to``: A list or tuple of recipient addresses.
231
232     * ``bcc``: A list or tuple of addresses used in the "Bcc" header when
233       sending the e-mail.
234
235     * ``connection``: An ``SMTPConnection`` instance. Use this parameter if
236       you want to use the same conneciton for multiple messages. If omitted, a
237       new connection is created when ``send()`` is called.
238
239     * ``attachments``: A list of attachments to put on the message. These can
240       be either ``email.MIMEBase.MIMEBase`` instances, or ``(filename,
241       content, mimetype)`` triples.
242
243     * ``headers``: A dictionary of extra headers to put on the message. The
244       keys are the header name, values are the header values. It's up to the
245       caller to ensure header names and values are in the correct format for
246       an e-mail message.
247
248 For example::
249
250     email = EmailMessage('Hello', 'Body goes here', 'from@example.com',
251                 ['to1@example.com', 'to2@example.com'], ['bcc@example.com'],
252                 headers = {'Reply-To': 'another@example.com'})
253
254 The class has the following methods:
255
256     * ``send()`` sends the message, using either the connection that is
257       specified in the ``connection`` attribute, or creating a new connection
258       if none already exists.
259
260     * ``message()`` constructs a ``django.core.mail.SafeMIMEText`` object (a
261       subclass of Python's ``email.MIMEText.MIMEText`` class) or a
262       ``django.core.mail.SafeMIMEMultipart`` object holding the
263       message to be sent. If you ever need to extend the ``EmailMessage`` class,
264       you'll probably want to override this method to put the content you want
265       into the MIME object.
266
267     * ``recipients()`` returns a list of all the recipients of the message,
268       whether they're recorded in the ``to`` or ``bcc`` attributes. This is
269       another method you might need to override when subclassing, because the
270       SMTP server needs to be told the full list of recipients when the message
271       is sent. If you add another way to specify recipients in your class, they
272       need to be returned from this method as well.
273
274     * ``attach()`` creates a new file attachment and adds it to the message.
275       There are two ways to call ``attach()``:
276
277        * You can pass it a single argument that is an
278          ``email.MIMBase.MIMEBase`` instance. This will be inserted directly
279          into the resulting message.
280
281        * Alternatively, you can pass ``attach()`` three arguments:
282          ``filename``, ``content`` and ``mimetype``. ``filename`` is the name
283          of the file attachment as it will appear in the e-mail, ``content`` is
284          the data that will be contained inside the attachment and
285          ``mimetype`` is the optional MIME type for the attachment. If you
286          omit ``mimetype``, the MIME content type will be guessed from the
287          filename of the attachment.
288
289          For example::
290
291             message.attach('design.png', img_data, 'image/png')
292
293     * ``attach_file()`` creates a new attachment using a file from your
294       filesystem. Call it with the path of the file to attach and, optionally,
295       the MIME type to use for the attachment. If the MIME type is omitted, it
296       will be guessed from the filename. The simplest use would be::
297
298         message.attach_file('/images/weather_map.png')
299
300 Sending alternative content types
301 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
302
303 It can be useful to include multiple versions of the content in an e-mail;
304 the classic example is to send both text and HTML versions of a message. With
305 Django's e-mail library, you can do this using the ``EmailMultiAlternatives``
306 class. This subclass of ``EmailMessage`` has an ``attach_alternative()`` method
307 for including extra versions of the message body in the e-mail. All the other
308 methods (including the class initialization) are inherited directly from
309 ``EmailMessage``.
310
311 To send a text and HTML combination, you could write::
312
313     from django.core.mail import EmailMultiAlternatives
314
315     subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
316     text_content = 'This is an important message.'
317     html_content = '<p>This is an <strong>important</strong> message.'
318     msg = EmailMultiAlternatives(subject, text_content, from_email, to)
319     msg.attach_alternative(html_content, "text/html")
320     msg.send()
321
322 By default, the MIME type of the ``body`` parameter in an ``EmailMessage`` is
323 ``"text/plain"``. It is good practice to leave this alone, because it
324 guarantees that any recipient will be able to read the e-mail, regardless of
325 their mail client. However, if you are confident that your recipients can
326 handle an alternative content type, you can use the ``content_subtype``
327 attribute on the ``EmailMessage`` class to change the main content type. The
328 major type will always be ``"text"``, but you can change it to the subtype. For
329 example::
330
331     msg = EmailMessage(subject, html_content, from_email, to)
332     msg.content_subtype = "html"  # Main content is now text/html
333     msg.send()
334
335 SMTP network connections
336 ------------------------
337
338 The ``SMTPConnection`` class is initialized with the host, port, username and
339 password for the SMTP server. If you don't specify one or more of those
340 options, they are read from your settings file.
341
342 If you're sending lots of messages at once, the ``send_messages()`` method of
343 the ``SMTPConnection`` class is useful. It takes a list of ``EmailMessage``
344 instances (or subclasses) and sends them over a single connection. For example,
345 if you have a function called ``get_notification_email()`` that returns a
346 list of ``EmailMessage`` objects representing some periodic e-mail you wish to
347 send out, you could send this with::
348
349     connection = SMTPConnection()   # Use default settings for connection
350     messages = get_notification_email()
351     connection.send_messages(messages)
Note: See TracBrowser for help on using the browser.