Although Python makes sending email relatively easy via the smtplib module, Django provides a couple of light wrappers over it. These wrappers are provided to make sending email extra quick, to make it easy to test email sending during development, and to provide support for platforms that can’t use SMTP.
The code lives in the django.core.mail module.
In two lines:
from django.core.mail import send_mail
send_mail('Subject here', 'Here is the message.', '[email protected]',
['[email protected]'], fail_silently=False)
Mail is sent using the SMTP host and port specified in the EMAIL_HOST and EMAIL_PORT settings. The EMAIL_HOST_USER and EMAIL_HOST_PASSWORD settings, if set, are used to authenticate to the SMTP server, and the EMAIL_USE_TLS setting controls whether a secure connection is used.
Note
The character set of email sent with django.core.mail will be set to the value of your DEFAULT_CHARSET setting.
The simplest way to send email is using django.core.mail.send_mail().
The subject, message, from_email and recipient_list parameters are required.
django.core.mail.send_mass_mail() is intended to handle mass emailing.
datatuple is a tuple in which each element is in this format:
(subject, message, from_email, recipient_list)
fail_silently, auth_user and auth_password have the same functions as in send_mail().
Each separate element of datatuple results in a separate email message. As in send_mail(), recipients in the same recipient_list will all see the other addresses in the email messages' "To:" field.
For example, the following code would send two different messages to two different sets of recipients; however, only one connection to the mail server would be opened:
message1 = ('Subject here', 'Here is the message', '[email protected]', ['[email protected]', '[email protected]'])
message2 = ('Another Subject', 'Here is another message', '[email protected]', ['[email protected]'])
send_mass_mail((message1, message2), fail_silently=False)
The main difference between send_mass_mail() and send_mail() is that send_mail() opens a connection to the mail server each time it's executed, while send_mass_mail() uses a single connection for all of its messages. This makes send_mass_mail() slightly more efficient.
django.core.mail.mail_admins() is a shortcut for sending an email to the site admins, as defined in the ADMINS setting.
mail_admins() prefixes the subject with the value of the EMAIL_SUBJECT_PREFIX setting, which is "[Django] " by default.
The "From:" header of the email will be the value of the SERVER_EMAIL setting.
This method exists for convenience and readability.
If html_message is provided, the resulting email will be a multipart/alternative email with message as the text/plain content type and html_message as the text/html content type.
django.core.mail.mail_managers() is just like mail_admins(), except it sends an email to the site managers, as defined in the MANAGERS setting.
This sends a single email to john@example.com and jane@example.com, with them both appearing in the "To:":
send_mail('Subject', 'Message.', '[email protected]',
['[email protected]', '[email protected]'])
This sends a message to john@example.com and jane@example.com, with them both receiving a separate email:
datatuple = (
('Subject', 'Message.', '[email protected]', ['[email protected]']),
('Subject', 'Message.', '[email protected]', ['[email protected]']),
)
send_mass_mail(datatuple)
Header injection is a security exploit in which an attacker inserts extra email headers to control the "To:" and "From:" in email messages that your scripts generate.
The Django email functions outlined above all protect against header injection by forbidding newlines in header values. If any subject, from_email or recipient_list contains a newline (in either Unix, Windows or Mac style), the email function (e.g. send_mail()) will raise django.core.mail.BadHeaderError (a subclass of ValueError) and, hence, will not send the email. It's your responsibility to validate all data before passing it to the email functions.
If a message contains headers at the start of the string, the headers will simply be printed as the first bit of the email message.
Here's an example view that takes a subject, message and from_email from the request's POST data, sends that to admin@example.com and redirects to "/contact/thanks/" when it's done:
from django.core.mail import send_mail, BadHeaderError
def send_email(request):
subject = request.POST.get('subject', '')
message = request.POST.get('message', '')
from_email = request.POST.get('from_email', '')
if subject and message and from_email:
try:
send_mail(subject, message, from_email, ['[email protected]'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return HttpResponseRedirect('/contact/thanks/')
else:
# In reality we'd use a form class
# to get proper validation errors.
return HttpResponse('Make sure all fields are entered and valid.')
Django's send_mail() and send_mass_mail() functions are actually thin wrappers that make use of the EmailMessage class.
Not all features of the EmailMessage class are available through the send_mail() and related wrapper functions. If you wish to use advanced features, such as BCC'ed recipients, file attachments, or multi-part email, you'll need to create EmailMessage instances directly.
Note
This is a design feature. send_mail() and related functions were originally the only interface Django provided. However, the list of parameters they accepted was slowly growing over time. It made sense to move to a more object-oriented design for email messages and retain the original functions only for backwards compatibility.
EmailMessage is responsible for creating the email message itself. The email backend is then responsible for sending the email.
For convenience, EmailMessage provides a simple send() method for sending a single email. If you need to send multiple messages, the email backend API provides an alternative.
The EmailMessage class is initialized with the following parameters (in the given order, if positional arguments are used). All parameters are optional and can be set at any time prior to calling the send() method.
For example:
email = EmailMessage('Hello', 'Body goes here', '[email protected]',
['[email protected]', '[email protected]'], ['[email protected]'],
headers = {'Reply-To': '[email protected]'})
The class has the following methods:
send(fail_silently=False) sends the message. If a connection was specified when the email was constructed, that connection will be used. Otherwise, an instance of the default backend will be instantiated and used. If the keyword argument fail_silently is True, exceptions raised while sending the message will be quashed.
message() constructs a django.core.mail.SafeMIMEText object (a subclass of Python's email.MIMEText.MIMEText class) or a django.core.mail.SafeMIMEMultipart object holding the message to be sent. If you ever need to extend the EmailMessage class, you'll probably want to override this method to put the content you want into the MIME object.
recipients() returns a list of all the recipients of the message, whether they're recorded in the to, cc or bcc attributes. This is another method you might need to override when subclassing, because the SMTP server needs to be told the full list of recipients when the message is sent. If you add another way to specify recipients in your class, they need to be returned from this method as well.
attach() creates a new file attachment and adds it to the message. There are two ways to call attach():
You can pass it a single argument that is an email.MIMEBase.MIMEBase instance. This will be inserted directly into the resulting message.
Alternatively, you can pass attach() three arguments: filename, content and mimetype. filename is the name of the file attachment as it will appear in the email, content is the data that will be contained inside the attachment and mimetype is the optional MIME type for the attachment. If you omit mimetype, the MIME content type will be guessed from the filename of the attachment.
For example:
message.attach('design.png', img_data, 'image/png')
attach_file() creates a new attachment using a file from your filesystem. Call it with the path of the file to attach and, optionally, the MIME type to use for the attachment. If the MIME type is omitted, it will be guessed from the filename. The simplest use would be:
message.attach_file('/images/weather_map.png')
It can be useful to include multiple versions of the content in an email; the classic example is to send both text and HTML versions of a message. With Django's email library, you can do this using the EmailMultiAlternatives class. This subclass of EmailMessage has an attach_alternative() method for including extra versions of the message body in the email. All the other methods (including the class initialization) are inherited directly from EmailMessage.
To send a text and HTML combination, you could write:
from django.core.mail import EmailMultiAlternatives
subject, from_email, to = 'hello', '[email protected]', '[email protected]'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
By default, the MIME type of the body parameter in an EmailMessage is "text/plain". It is good practice to leave this alone, because it guarantees that any recipient will be able to read the email, regardless of their mail client. However, if you are confident that your recipients can handle an alternative content type, you can use the content_subtype attribute on the EmailMessage class to change the main content type. The major type will always be "text", but you can change the subtype. For example:
msg = EmailMessage(subject, html_content, from_email, [to])
msg.content_subtype = "html" # Main content is now text/html
msg.send()
The actual sending of an email is handled by the email backend.
The email backend class has the following methods:
The get_connection() function in django.core.mail returns an instance of the email backend that you can use.
By default, a call to get_connection() will return an instance of the email backend specified in EMAIL_BACKEND. If you specify the backend argument, an instance of that backend will be instantiated.
The fail_silently argument controls how the backend should handle errors. If fail_silently is True, exceptions during the email sending process will be silently ignored.
All other arguments are passed directly to the constructor of the email backend.
Django ships with several email sending backends. With the exception of the SMTP backend (which is the default), these backends are only useful during testing and development. If you have special email sending requirements, you can write your own email backend.
This is the default backend. Email will be sent through a SMTP server. The server address and authentication credentials are set in the EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER, EMAIL_HOST_PASSWORD and EMAIL_USE_TLS settings in your settings file.
The SMTP backend is the default configuration inherited by Django. If you want to specify it explicitly, put the following in your settings:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
Instead of sending out real emails the console backend just writes the emails that would be send to the standard output. By default, the console backend writes to stdout. You can use a different stream-like object by providing the stream keyword argument when constructing the connection.
To specify this backend, put the following in your settings:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
This backend is not intended for use in production -- it is provided as a convenience that can be used during development.
The file backend writes emails to a file. A new file is created for each new session that is opened on this backend. The directory to which the files are written is either taken from the EMAIL_FILE_PATH setting or from the file_path keyword when creating a connection with get_connection().
To specify this backend, put the following in your settings:
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = '/tmp/app-messages' # change this to a proper location
This backend is not intended for use in production -- it is provided as a convenience that can be used during development.
The 'locmem' backend stores messages in a special attribute of the django.core.mail module. The outbox attribute is created when the first message is sent. It's a list with an EmailMessage instance for each message that would be send.
To specify this backend, put the following in your settings:
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
This backend is not intended for use in production -- it is provided as a convenience that can be used during development and testing.
As the name suggests the dummy backend does nothing with your messages. To specify this backend, put the following in your settings:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
This backend is not intended for use in production -- it is provided as a convenience that can be used during development.
If you need to change how emails are sent you can write your own email backend. The EMAIL_BACKEND setting in your settings file is then the Python import path for your backend class.
Custom email backends should subclass BaseEmailBackend that is located in the django.core.mail.backends.base module. A custom email backend must implement the send_messages(email_messages) method. This method receives a list of EmailMessage instances and returns the number of successfully delivered messages. If your backend has any concept of a persistent session or connection, you should also implement the open() and close() methods. Refer to smtp.EmailBackend for a reference implementation.
Establishing and closing an SMTP connection (or any other network connection, for that matter) is an expensive process. If you have a lot of emails to send, it makes sense to reuse an SMTP connection, rather than creating and destroying a connection every time you want to send an email.
There are two ways you tell an email backend to reuse a connection.
Firstly, you can use the send_messages() method. send_messages() takes a list of EmailMessage instances (or subclasses), and sends them all using a single connection.
For example, if you have a function called get_notification_email() that returns a list of EmailMessage objects representing some periodic email you wish to send out, you could send these emails using a single call to send_messages:
from django.core import mail
connection = mail.get_connection() # Use default email connection
messages = get_notification_email()
connection.send_messages(messages)
In this example, the call to send_messages() opens a connection on the backend, sends the list of messages, and then closes the connection again.
The second approach is to use the open() and close() methods on the email backend to manually control the connection. send_messages() will not manually open or close the connection if it is already open, so if you manually open the connection, you can control when it is closed. For example:
from django.core import mail
connection = mail.get_connection()
# Manually open the connection
connection.open()
# Construct an email message that uses the connection
email1 = mail.EmailMessage('Hello', 'Body goes here', '[email protected]',
['[email protected]'], connection=connection)
email1.send() # Send the email
# Construct two more messages
email2 = mail.EmailMessage('Hello', 'Body goes here', '[email protected]',
['[email protected]'])
email3 = mail.EmailMessage('Hello', 'Body goes here', '[email protected]',
['[email protected]'])
# Send the two emails in a single call -
connection.send_messages([email2, email3])
# The connection was already open so send_messages() doesn't close it.
# We need to manually close the connection.
connection.close()
There are times when you do not want Django to send emails at all. For example, while developing a Web site, you probably don't want to send out thousands of emails -- but you may want to validate that emails will be sent to the right people under the right conditions, and that those emails will contain the correct content.
The easiest way to test your project's use of email is to use the console email backend. This backend redirects all email to stdout, allowing you to inspect the content of mail.
The file email backend can also be useful during development -- this backend dumps the contents of every SMTP connection to a file that can be inspected at your leisure.
Another approach is to use a "dumb" SMTP server that receives the emails locally and displays them to the terminal, but does not actually send anything. Python has a built-in way to accomplish this with a single command:
python -m smtpd -n -c DebuggingServer localhost:1025
This command will start a simple SMTP server listening on port 1025 of localhost. This server simply prints to standard output all email headers and the email body. You then only need to set the EMAIL_HOST and EMAIL_PORT accordingly, and you are set.
For a more detailed discussion of testing and processing of emails locally, see the Python documentation for the smtpd module.
May 10, 2012