| 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: ../settings/#admins |
|---|
| 115 |
.. _EMAIL_SUBJECT_PREFIX: ../settings/#email-subject-prefix |
|---|
| 116 |
.. _SERVER_EMAIL: ../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: ../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(fail_silently=False)`` sends the message, using either |
|---|
| 257 |
the connection that is specified in the ``connection`` |
|---|
| 258 |
attribute, or creating a new connection if none already |
|---|
| 259 |
exists. If the keyword argument ``fail_silently`` is ``True``, |
|---|
| 260 |
exceptions raised while sending the message will be quashed. |
|---|
| 261 |
|
|---|
| 262 |
* ``message()`` constructs a ``django.core.mail.SafeMIMEText`` object (a |
|---|
| 263 |
subclass of Python's ``email.MIMEText.MIMEText`` class) or a |
|---|
| 264 |
``django.core.mail.SafeMIMEMultipart`` object holding the |
|---|
| 265 |
message to be sent. If you ever need to extend the ``EmailMessage`` class, |
|---|
| 266 |
you'll probably want to override this method to put the content you want |
|---|
| 267 |
into the MIME object. |
|---|
| 268 |
|
|---|
| 269 |
* ``recipients()`` returns a list of all the recipients of the message, |
|---|
| 270 |
whether they're recorded in the ``to`` or ``bcc`` attributes. This is |
|---|
| 271 |
another method you might need to override when subclassing, because the |
|---|
| 272 |
SMTP server needs to be told the full list of recipients when the message |
|---|
| 273 |
is sent. If you add another way to specify recipients in your class, they |
|---|
| 274 |
need to be returned from this method as well. |
|---|
| 275 |
|
|---|
| 276 |
* ``attach()`` creates a new file attachment and adds it to the message. |
|---|
| 277 |
There are two ways to call ``attach()``: |
|---|
| 278 |
|
|---|
| 279 |
* You can pass it a single argument that is an |
|---|
| 280 |
``email.MIMEBase.MIMEBase`` instance. This will be inserted directly |
|---|
| 281 |
into the resulting message. |
|---|
| 282 |
|
|---|
| 283 |
* Alternatively, you can pass ``attach()`` three arguments: |
|---|
| 284 |
``filename``, ``content`` and ``mimetype``. ``filename`` is the name |
|---|
| 285 |
of the file attachment as it will appear in the e-mail, ``content`` is |
|---|
| 286 |
the data that will be contained inside the attachment and |
|---|
| 287 |
``mimetype`` is the optional MIME type for the attachment. If you |
|---|
| 288 |
omit ``mimetype``, the MIME content type will be guessed from the |
|---|
| 289 |
filename of the attachment. |
|---|
| 290 |
|
|---|
| 291 |
For example:: |
|---|
| 292 |
|
|---|
| 293 |
message.attach('design.png', img_data, 'image/png') |
|---|
| 294 |
|
|---|
| 295 |
* ``attach_file()`` creates a new attachment using a file from your |
|---|
| 296 |
filesystem. Call it with the path of the file to attach and, optionally, |
|---|
| 297 |
the MIME type to use for the attachment. If the MIME type is omitted, it |
|---|
| 298 |
will be guessed from the filename. The simplest use would be:: |
|---|
| 299 |
|
|---|
| 300 |
message.attach_file('/images/weather_map.png') |
|---|
| 301 |
|
|---|
| 302 |
.. _DEFAULT_FROM_EMAIL: ../settings/#default-from-email |
|---|
| 303 |
|
|---|
| 304 |
Sending alternative content types |
|---|
| 305 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|---|
| 306 |
|
|---|
| 307 |
It can be useful to include multiple versions of the content in an e-mail; |
|---|
| 308 |
the classic example is to send both text and HTML versions of a message. With |
|---|
| 309 |
Django's e-mail library, you can do this using the ``EmailMultiAlternatives`` |
|---|
| 310 |
class. This subclass of ``EmailMessage`` has an ``attach_alternative()`` method |
|---|
| 311 |
for including extra versions of the message body in the e-mail. All the other |
|---|
| 312 |
methods (including the class initialization) are inherited directly from |
|---|
| 313 |
``EmailMessage``. |
|---|
| 314 |
|
|---|
| 315 |
To send a text and HTML combination, you could write:: |
|---|
| 316 |
|
|---|
| 317 |
from django.core.mail import EmailMultiAlternatives |
|---|
| 318 |
|
|---|
| 319 |
subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' |
|---|
| 320 |
text_content = 'This is an important message.' |
|---|
| 321 |
html_content = '<p>This is an <strong>important</strong> message.</p>' |
|---|
| 322 |
msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) |
|---|
| 323 |
msg.attach_alternative(html_content, "text/html") |
|---|
| 324 |
msg.send() |
|---|
| 325 |
|
|---|
| 326 |
By default, the MIME type of the ``body`` parameter in an ``EmailMessage`` is |
|---|
| 327 |
``"text/plain"``. It is good practice to leave this alone, because it |
|---|
| 328 |
guarantees that any recipient will be able to read the e-mail, regardless of |
|---|
| 329 |
their mail client. However, if you are confident that your recipients can |
|---|
| 330 |
handle an alternative content type, you can use the ``content_subtype`` |
|---|
| 331 |
attribute on the ``EmailMessage`` class to change the main content type. The |
|---|
| 332 |
major type will always be ``"text"``, but you can change it to the subtype. For |
|---|
| 333 |
example:: |
|---|
| 334 |
|
|---|
| 335 |
msg = EmailMessage(subject, html_content, from_email, [to]) |
|---|
| 336 |
msg.content_subtype = "html" # Main content is now text/html |
|---|
| 337 |
msg.send() |
|---|
| 338 |
|
|---|
| 339 |
SMTP network connections |
|---|
| 340 |
------------------------ |
|---|
| 341 |
|
|---|
| 342 |
The ``SMTPConnection`` class is initialized with the host, port, username and |
|---|
| 343 |
password for the SMTP server. If you don't specify one or more of those |
|---|
| 344 |
options, they are read from your settings file. |
|---|
| 345 |
|
|---|
| 346 |
If you're sending lots of messages at once, the ``send_messages()`` method of |
|---|
| 347 |
the ``SMTPConnection`` class is useful. It takes a list of ``EmailMessage`` |
|---|
| 348 |
instances (or subclasses) and sends them over a single connection. For example, |
|---|
| 349 |
if you have a function called ``get_notification_email()`` that returns a |
|---|
| 350 |
list of ``EmailMessage`` objects representing some periodic e-mail you wish to |
|---|
| 351 |
send out, you could send this with:: |
|---|
| 352 |
|
|---|
| 353 |
connection = SMTPConnection() # Use default settings for connection |
|---|
| 354 |
messages = get_notification_email() |
|---|
| 355 |
connection.send_messages(messages) |
|---|