Kaydet (Commit) aba53893 authored tarafından Russell Keith-Magee's avatar Russell Keith-Magee

Fixed #10355 -- Added an API for pluggable e-mail backends.

Thanks to Andi Albrecht for his work on this patch, and to everyone else that contributed during design and development.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@11709 bcc190cf-cafb-0310-a4f2-bffc1f526a37
üst 8287c27b
......@@ -27,6 +27,7 @@ answer newbie questions, and generally made Django that much better:
ajs <adi@sieker.info>
alang@bright-green.com
Andi Albrecht <albrecht.andi@gmail.com>
Marty Alchin <gulopine@gamemusic.org>
Ahmad Alhashemi <trans@ahmadh.com>
Daniel Alves Barbosa de Oliveira Vaz <danielvaz@gmail.com>
......
......@@ -131,6 +131,12 @@ DATABASE_HOST = '' # Set to empty string for localhost. Not used wit
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
DATABASE_OPTIONS = {} # Set to empty dictionary for default.
# The email backend to use. For possible shortcuts see django.core.mail.
# The default is to use the SMTP backend.
# Third-party backends can be specified by providing a Python path
# to a module that defines an EmailBackend class.
EMAIL_BACKEND = 'django.core.mail.backends.smtp'
# Host for sending e-mail.
EMAIL_HOST = 'localhost'
......
"""
Tools for sending email.
"""
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
# Imported for backwards compatibility, and for the sake
# of a cleaner namespace. These symbols used to be in
# django/core/mail.py before the introduction of email
# backends and the subsequent reorganization (See #10355)
from django.core.mail.utils import CachedDnsName, DNS_NAME
from django.core.mail.message import \
EmailMessage, EmailMultiAlternatives, \
SafeMIMEText, SafeMIMEMultipart, \
DEFAULT_ATTACHMENT_MIME_TYPE, make_msgid, \
BadHeaderError, forbid_multi_line_headers
from django.core.mail.backends.smtp import EmailBackend as _SMTPConnection
def get_connection(backend=None, fail_silently=False, **kwds):
"""Load an e-mail backend and return an instance of it.
If backend is None (default) settings.EMAIL_BACKEND is used.
Both fail_silently and other keyword arguments are used in the
constructor of the backend.
"""
path = backend or settings.EMAIL_BACKEND
try:
mod = import_module(path)
except ImportError, e:
raise ImproperlyConfigured(('Error importing email backend %s: "%s"'
% (path, e)))
try:
cls = getattr(mod, 'EmailBackend')
except AttributeError:
raise ImproperlyConfigured(('Module "%s" does not define a '
'"EmailBackend" class' % path))
return cls(fail_silently=fail_silently, **kwds)
def send_mail(subject, message, from_email, recipient_list,
fail_silently=False, auth_user=None, auth_password=None,
connection=None):
"""
Easy wrapper for sending a single message to a recipient list. All members
of the recipient list will see the other recipients in the 'To' field.
If auth_user is None, the EMAIL_HOST_USER setting is used.
If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
Note: The API for this method is frozen. New code wanting to extend the
functionality should use the EmailMessage class directly.
"""
connection = connection or get_connection(username=auth_user,
password=auth_password,
fail_silently=fail_silently)
return EmailMessage(subject, message, from_email, recipient_list,
connection=connection).send()
def send_mass_mail(datatuple, fail_silently=False, auth_user=None,
auth_password=None, connection=None):
"""
Given a datatuple of (subject, message, from_email, recipient_list), sends
each message to each recipient list. Returns the number of e-mails sent.
If from_email is None, the DEFAULT_FROM_EMAIL setting is used.
If auth_user and auth_password are set, they're used to log in.
If auth_user is None, the EMAIL_HOST_USER setting is used.
If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
Note: The API for this method is frozen. New code wanting to extend the
functionality should use the EmailMessage class directly.
"""
connection = connection or get_connection(username=auth_user,
password=auth_password,
fail_silently=fail_silently)
messages = [EmailMessage(subject, message, sender, recipient)
for subject, message, sender, recipient in datatuple]
return connection.send_messages(messages)
def mail_admins(subject, message, fail_silently=False, connection=None):
"""Sends a message to the admins, as defined by the ADMINS setting."""
if not settings.ADMINS:
return
EmailMessage(settings.EMAIL_SUBJECT_PREFIX + subject, message,
settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS],
connection=connection).send(fail_silently=fail_silently)
def mail_managers(subject, message, fail_silently=False, connection=None):
"""Sends a message to the managers, as defined by the MANAGERS setting."""
if not settings.MANAGERS:
return
EmailMessage(settings.EMAIL_SUBJECT_PREFIX + subject, message,
settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS],
connection=connection).send(fail_silently=fail_silently)
class SMTPConnection(_SMTPConnection):
def __init__(self, *args, **kwds):
import warnings
warnings.warn(
'mail.SMTPConnection is deprecated; use mail.get_connection() instead.',
DeprecationWarning
)
super(SMTPConnection, self).__init__(*args, **kwds)
# Mail backends shipped with Django.
"""Base email backend class."""
class BaseEmailBackend(object):
"""
Base class for email backend implementations.
Subclasses must at least overwrite send_messages().
"""
def __init__(self, fail_silently=False, **kwargs):
self.fail_silently = fail_silently
def open(self):
"""Open a network connection.
This method can be overwritten by backend implementations to
open a network connection.
It's up to the backend implementation to track the status of
a network connection if it's needed by the backend.
This method can be called by applications to force a single
network connection to be used when sending mails. See the
send_messages() method of the SMTP backend for a reference
implementation.
The default implementation does nothing.
"""
pass
def close(self):
"""Close a network connection."""
pass
def send_messages(self, email_messages):
"""
Sends one or more EmailMessage objects and returns the number of email
messages sent.
"""
raise NotImplementedError
"""
Email backend that writes messages to console instead of sending them.
"""
import sys
import threading
from django.core.mail.backends.base import BaseEmailBackend
class EmailBackend(BaseEmailBackend):
def __init__(self, *args, **kwargs):
self.stream = kwargs.pop('stream', sys.stdout)
self._lock = threading.RLock()
super(EmailBackend, self).__init__(*args, **kwargs)
def send_messages(self, email_messages):
"""Write all messages to the stream in a thread-safe way."""
if not email_messages:
return
self._lock.acquire()
try:
stream_created = self.open()
for message in email_messages:
self.stream.write('%s\n' % message.message().as_string())
self.stream.write('-'*79)
self.stream.write('\n')
self.stream.flush() # flush after each message
if stream_created:
self.close()
except:
if not self.fail_silently:
raise
finally:
self._lock.release()
return len(email_messages)
"""
Dummy email backend that does nothing.
"""
from django.core.mail.backends.base import BaseEmailBackend
class EmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
return len(email_messages)
"""Email backend that writes messages to a file."""
import datetime
import os
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.mail.backends.console import EmailBackend as ConsoleEmailBackend
class EmailBackend(ConsoleEmailBackend):
def __init__(self, *args, **kwargs):
self._fname = None
if 'file_path' in kwargs:
self.file_path = kwargs.pop('file_path')
else:
self.file_path = getattr(settings, 'EMAIL_FILE_PATH',None)
# Make sure self.file_path is a string.
if not isinstance(self.file_path, basestring):
raise ImproperlyConfigured('Path for saving emails is invalid: %r' % self.file_path)
self.file_path = os.path.abspath(self.file_path)
# Make sure that self.file_path is an directory if it exists.
if os.path.exists(self.file_path) and not os.path.isdir(self.file_path):
raise ImproperlyConfigured('Path for saving email messages exists, but is not a directory: %s' % self.file_path)
# Try to create it, if it not exists.
elif not os.path.exists(self.file_path):
try:
os.makedirs(self.file_path)
except OSError, err:
raise ImproperlyConfigured('Could not create directory for saving email messages: %s (%s)' % (self.file_path, err))
# Make sure that self.file_path is writable.
if not os.access(self.file_path, os.W_OK):
raise ImproperlyConfigured('Could not write to directory: %s' % self.file_path)
# Finally, call super().
# Since we're using the console-based backend as a base,
# force the stream to be None, so we don't default to stdout
kwargs['stream'] = None
super(EmailBackend, self).__init__(*args, **kwargs)
def _get_filename(self):
"""Return a unique file name."""
if self._fname is None:
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
fname = "%s-%s.log" % (timestamp, abs(id(self)))
self._fname = os.path.join(self.file_path, fname)
return self._fname
def open(self):
if self.stream is None:
self.stream = open(self._get_filename(), 'a')
return True
return False
def close(self):
try:
if self.stream is not None:
self.stream.close()
finally:
self.stream = None
"""
Backend for test environment.
"""
from django.core import mail
from django.core.mail.backends.base import BaseEmailBackend
class EmailBackend(BaseEmailBackend):
"""A email backend for use during test sessions.
The test connection stores email messages in a dummy outbox,
rather than sending them out on the wire.
The dummy outbox is accessible through the outbox instance attribute.
"""
def __init__(self, *args, **kwargs):
super(EmailBackend, self).__init__(*args, **kwargs)
if not hasattr(mail, 'outbox'):
mail.outbox = []
def send_messages(self, messages):
"""Redirect messages to the dummy outbox"""
mail.outbox.extend(messages)
return len(messages)
"""SMTP email backend class."""
import smtplib
import socket
import threading
from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail.utils import DNS_NAME
class EmailBackend(BaseEmailBackend):
"""
A wrapper that manages the SMTP network connection.
"""
def __init__(self, host=None, port=None, username=None, password=None,
use_tls=None, fail_silently=False, **kwargs):
super(EmailBackend, self).__init__(fail_silently=fail_silently)
self.host = host or settings.EMAIL_HOST
self.port = port or settings.EMAIL_PORT
self.username = username or settings.EMAIL_HOST_USER
self.password = password or settings.EMAIL_HOST_PASSWORD
self.use_tls = (use_tls is not None) and use_tls or settings.EMAIL_USE_TLS
self.connection = None
self._lock = threading.RLock()
def open(self):
"""
Ensures we have a connection to the email server. Returns whether or
not a new connection was required (True or False).
"""
if self.connection:
# Nothing to do if the connection is already open.
return False
try:
# If local_hostname is not specified, socket.getfqdn() gets used.
# For performance, we use the cached FQDN for local_hostname.
self.connection = smtplib.SMTP(self.host, self.port,
local_hostname=DNS_NAME.get_fqdn())
if self.use_tls:
self.connection.ehlo()
self.connection.starttls()
self.connection.ehlo()
if self.username and self.password:
self.connection.login(self.username, self.password)
return True
except:
if not self.fail_silently:
raise
def close(self):
"""Closes the connection to the email server."""
try:
try:
self.connection.quit()
except socket.sslerror:
# This happens when calling quit() on a TLS connection
# sometimes.
self.connection.close()
except:
if self.fail_silently:
return
raise
finally:
self.connection = None
def send_messages(self, email_messages):
"""
Sends one or more EmailMessage objects and returns the number of email
messages sent.
"""
if not email_messages:
return
self._lock.acquire()
try:
new_conn_created = self.open()
if not self.connection:
# We failed silently on open().
# Trying to send would be pointless.
return
num_sent = 0
for message in email_messages:
sent = self._send(message)
if sent:
num_sent += 1
if new_conn_created:
self.close()
finally:
self._lock.release()
return num_sent
def _send(self, email_message):
"""A helper method that does the actual sending."""
if not email_message.recipients():
return False
try:
self.connection.sendmail(email_message.from_email,
email_message.recipients(),
email_message.message().as_string())
except:
if not self.fail_silently:
raise
return False
return True
"""
Tools for sending email.
"""
import mimetypes
import os
import smtplib
import socket
import time
import random
import time
from email import Charset, Encoders
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
......@@ -16,6 +10,7 @@ from email.Header import Header
from email.Utils import formatdate, parseaddr, formataddr
from django.conf import settings
from django.core.mail.utils import DNS_NAME
from django.utils.encoding import smart_str, force_unicode
# Don't BASE64-encode UTF-8 messages so that we avoid unwanted attention from
......@@ -26,18 +21,10 @@ Charset.add_charset('utf-8', Charset.SHORTEST, Charset.QP, 'utf-8')
# and cannot be guessed).
DEFAULT_ATTACHMENT_MIME_TYPE = 'application/octet-stream'
# Cache the hostname, but do it lazily: socket.getfqdn() can take a couple of
# seconds, which slows down the restart of the server.
class CachedDnsName(object):
def __str__(self):
return self.get_fqdn()
def get_fqdn(self):
if not hasattr(self, '_fqdn'):
self._fqdn = socket.getfqdn()
return self._fqdn
class BadHeaderError(ValueError):
pass
DNS_NAME = CachedDnsName()
# Copied from Python standard library, with the following modifications:
# * Used cached hostname for performance.
......@@ -66,8 +53,6 @@ def make_msgid(idstring=None):
msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
return msgid
class BadHeaderError(ValueError):
pass
def forbid_multi_line_headers(name, val):
"""Forbids multi-line headers, to prevent header injection."""
......@@ -91,104 +76,18 @@ def forbid_multi_line_headers(name, val):
val = Header(val)
return name, val
class SafeMIMEText(MIMEText):
def __setitem__(self, name, val):
name, val = forbid_multi_line_headers(name, val)
MIMEText.__setitem__(self, name, val)
class SafeMIMEMultipart(MIMEMultipart):
def __setitem__(self, name, val):
name, val = forbid_multi_line_headers(name, val)
MIMEMultipart.__setitem__(self, name, val)
class SMTPConnection(object):
"""
A wrapper that manages the SMTP network connection.
"""
def __init__(self, host=None, port=None, username=None, password=None,
use_tls=None, fail_silently=False):
self.host = host or settings.EMAIL_HOST
self.port = port or settings.EMAIL_PORT
self.username = username or settings.EMAIL_HOST_USER
self.password = password or settings.EMAIL_HOST_PASSWORD
self.use_tls = (use_tls is not None) and use_tls or settings.EMAIL_USE_TLS
self.fail_silently = fail_silently
self.connection = None
def open(self):
"""
Ensures we have a connection to the email server. Returns whether or
not a new connection was required (True or False).
"""
if self.connection:
# Nothing to do if the connection is already open.
return False
try:
# If local_hostname is not specified, socket.getfqdn() gets used.
# For performance, we use the cached FQDN for local_hostname.
self.connection = smtplib.SMTP(self.host, self.port,
local_hostname=DNS_NAME.get_fqdn())
if self.use_tls:
self.connection.ehlo()
self.connection.starttls()
self.connection.ehlo()
if self.username and self.password:
self.connection.login(self.username, self.password)
return True
except:
if not self.fail_silently:
raise
def close(self):
"""Closes the connection to the email server."""
try:
try:
self.connection.quit()
except socket.sslerror:
# This happens when calling quit() on a TLS connection
# sometimes.
self.connection.close()
except:
if self.fail_silently:
return
raise
finally:
self.connection = None
def send_messages(self, email_messages):
"""
Sends one or more EmailMessage objects and returns the number of email
messages sent.
"""
if not email_messages:
return
new_conn_created = self.open()
if not self.connection:
# We failed silently on open(). Trying to send would be pointless.
return
num_sent = 0
for message in email_messages:
sent = self._send(message)
if sent:
num_sent += 1
if new_conn_created:
self.close()
return num_sent
def _send(self, email_message):
"""A helper method that does the actual sending."""
if not email_message.recipients():
return False
try:
self.connection.sendmail(email_message.from_email,
email_message.recipients(),
email_message.message().as_string())
except:
if not self.fail_silently:
raise
return False
return True
class EmailMessage(object):
"""
......@@ -199,14 +98,14 @@ class EmailMessage(object):
encoding = None # None => use settings default
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
connection=None, attachments=None, headers=None):
connection=None, attachments=None, headers=None):
"""
Initialize a single email message (which can be sent to multiple
recipients).
All strings used to create the message can be unicode strings (or UTF-8
bytestrings). The SafeMIMEText class will handle any necessary encoding
conversions.
All strings used to create the message can be unicode strings
(or UTF-8 bytestrings). The SafeMIMEText class will handle any
necessary encoding conversions.
"""
if to:
assert not isinstance(to, basestring), '"to" argument must be a list or tuple'
......@@ -226,8 +125,9 @@ class EmailMessage(object):
self.connection = connection
def get_connection(self, fail_silently=False):
from django.core.mail import get_connection
if not self.connection:
self.connection = SMTPConnection(fail_silently=fail_silently)
self.connection = get_connection(fail_silently=fail_silently)
return self.connection
def message(self):
......@@ -332,6 +232,7 @@ class EmailMessage(object):
filename=filename)
return attachment
class EmailMultiAlternatives(EmailMessage):
"""
A version of EmailMessage that makes it easy to send multipart/alternative
......@@ -371,56 +272,3 @@ class EmailMultiAlternatives(EmailMessage):
for alternative in self.alternatives:
msg.attach(self._create_mime_attachment(*alternative))
return msg
def send_mail(subject, message, from_email, recipient_list,
fail_silently=False, auth_user=None, auth_password=None):
"""
Easy wrapper for sending a single message to a recipient list. All members
of the recipient list will see the other recipients in the 'To' field.
If auth_user is None, the EMAIL_HOST_USER setting is used.
If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
Note: The API for this method is frozen. New code wanting to extend the
functionality should use the EmailMessage class directly.
"""
connection = SMTPConnection(username=auth_user, password=auth_password,
fail_silently=fail_silently)
return EmailMessage(subject, message, from_email, recipient_list,
connection=connection).send()
def send_mass_mail(datatuple, fail_silently=False, auth_user=None,
auth_password=None):
"""
Given a datatuple of (subject, message, from_email, recipient_list), sends
each message to each recipient list. Returns the number of e-mails sent.
If from_email is None, the DEFAULT_FROM_EMAIL setting is used.
If auth_user and auth_password are set, they're used to log in.
If auth_user is None, the EMAIL_HOST_USER setting is used.
If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
Note: The API for this method is frozen. New code wanting to extend the
functionality should use the EmailMessage class directly.
"""
connection = SMTPConnection(username=auth_user, password=auth_password,
fail_silently=fail_silently)
messages = [EmailMessage(subject, message, sender, recipient)
for subject, message, sender, recipient in datatuple]
return connection.send_messages(messages)
def mail_admins(subject, message, fail_silently=False):
"""Sends a message to the admins, as defined by the ADMINS setting."""
if not settings.ADMINS:
return
EmailMessage(settings.EMAIL_SUBJECT_PREFIX + subject, message,
settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS]
).send(fail_silently=fail_silently)
def mail_managers(subject, message, fail_silently=False):
"""Sends a message to the managers, as defined by the MANAGERS setting."""
if not settings.MANAGERS:
return
EmailMessage(settings.EMAIL_SUBJECT_PREFIX + subject, message,
settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS]
).send(fail_silently=fail_silently)
"""
Email message and email sending related helper functions.
"""
import socket
# Cache the hostname, but do it lazily: socket.getfqdn() can take a couple of
# seconds, which slows down the restart of the server.
class CachedDnsName(object):
def __str__(self):
return self.get_fqdn()
def get_fqdn(self):
if not hasattr(self, '_fqdn'):
self._fqdn = socket.getfqdn()
return self._fqdn
DNS_NAME = CachedDnsName()
......@@ -2,6 +2,7 @@ import sys, time, os
from django.conf import settings
from django.db import connection
from django.core import mail
from django.core.mail.backends import locmem
from django.test import signals
from django.template import Template
from django.utils.translation import deactivate
......@@ -28,37 +29,22 @@ def instrumented_test_render(self, context):
signals.template_rendered.send(sender=self, template=self, context=context)
return self.nodelist.render(context)
class TestSMTPConnection(object):
"""A substitute SMTP connection for use during test sessions.
The test connection stores email messages in a dummy outbox,
rather than sending them out on the wire.
"""
def __init__(*args, **kwargs):
pass
def open(self):
"Mock the SMTPConnection open() interface"
pass
def close(self):
"Mock the SMTPConnection close() interface"
pass
def send_messages(self, messages):
"Redirect messages to the dummy outbox"
mail.outbox.extend(messages)
return len(messages)
def setup_test_environment():
"""Perform any global pre-test setup. This involves:
- Installing the instrumented test renderer
- Diverting the email sending functions to a test buffer
- Set the email backend to the locmem email backend.
- Setting the active locale to match the LANGUAGE_CODE setting.
"""
Template.original_render = Template.render
Template.render = instrumented_test_render
mail.original_SMTPConnection = mail.SMTPConnection
mail.SMTPConnection = TestSMTPConnection
mail.SMTPConnection = locmem.EmailBackend
settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem'
mail.original_email_backend = settings.EMAIL_BACKEND
mail.outbox = []
......@@ -77,8 +63,10 @@ def teardown_test_environment():
mail.SMTPConnection = mail.original_SMTPConnection
del mail.original_SMTPConnection
del mail.outbox
settings.EMAIL_BACKEND = mail.original_email_backend
del mail.original_email_backend
del mail.outbox
def get_runner(settings):
test_path = settings.TEST_RUNNER.split('.')
......
......@@ -22,6 +22,9 @@ their deprecation, as per the :ref:`Django deprecation policy
* The old imports for CSRF functionality (``django.contrib.csrf.*``),
which moved to core in 1.2, will be removed.
* ``SMTPConnection``. The 1.2 release deprecated the ``SMTPConnection``
class in favor of a generic E-mail backend API.
* 2.0
* ``django.views.defaults.shortcut()``. This function has been moved
to ``django.contrib.contenttypes.views.shortcut()`` as part of the
......
......@@ -424,6 +424,29 @@ are not allowed to visit any page, systemwide. Use this for bad robots/crawlers.
This is only used if ``CommonMiddleware`` is installed (see
:ref:`topics-http-middleware`).
.. setting:: EMAIL_BACKEND
EMAIL_BACKEND
-------------
.. versionadded:: 1.2
Default: ``'smtp'``
The backend to use for sending emails. For the list of available backends see
:ref:`topics-email`.
.. setting:: EMAIL_FILE_PATH
EMAIL_FILE_PATH
---------------
.. versionadded:: 1.2
Default: Not defined
The directory used by the ``file`` email backend to store output files.
.. setting:: EMAIL_HOST
EMAIL_HOST
......
This diff is collapsed.
......@@ -1104,6 +1104,8 @@ applications:
``target_status_code`` will be the url and status code for the final
point of the redirect chain.
.. _topics-testing-email:
E-mail services
---------------
......@@ -1117,7 +1119,7 @@ test every aspect of sending e-mail -- from the number of messages sent to the
contents of each message -- without actually sending the messages.
The test runner accomplishes this by transparently replacing the normal
:class:`~django.core.mail.SMTPConnection` class with a different version.
email backend with a testing backend.
(Don't worry -- this has no effect on any other e-mail senders outside of
Django, such as your machine's mail server, if you're running one.)
......@@ -1128,14 +1130,8 @@ Django, such as your machine's mail server, if you're running one.)
During test running, each outgoing e-mail is saved in
``django.core.mail.outbox``. This is a simple list of all
:class:`~django.core.mail.EmailMessage` instances that have been sent.
It does not exist under normal execution conditions, i.e., when you're not
running unit tests. The outbox is created during test setup, along with the
dummy :class:`~django.core.mail.SMTPConnection`. When the test framework is
torn down, the standard :class:`~django.core.mail.SMTPConnection` class is
restored, and the test outbox is destroyed.
The ``outbox`` attribute is a special attribute that is created *only* when
the tests are run. It doesn't normally exist as part of the
the ``locmem`` e-mail backend is used. It doesn't normally exist as part of the
:mod:`django.core.mail` module and you can't import it directly. The code
below shows how to access this attribute correctly.
......
"""A custom backend for testing."""
from django.core.mail.backends.base import BaseEmailBackend
class EmailBackend(BaseEmailBackend):
def __init__(self, *args, **kwargs):
super(EmailBackend, self).__init__(*args, **kwargs)
self.test_outbox = []
def send_messages(self, email_messages):
# Messages are stored in a instance variable for testing.
self.test_outbox.extend(email_messages)
return len(email_messages)
# coding: utf-8
r"""
# Tests for the django.core.mail.
>>> import os
>>> import shutil
>>> import tempfile
>>> from StringIO import StringIO
>>> from django.conf import settings
>>> from django.core import mail
>>> from django.core.mail import EmailMessage, mail_admins, mail_managers, EmailMultiAlternatives
>>> from django.core.mail import send_mail, send_mass_mail
>>> from django.core.mail.backends.base import BaseEmailBackend
>>> from django.core.mail.backends import console, dummy, locmem, filebased, smtp
>>> from django.utils.translation import ugettext_lazy
# Test normal ascii character case:
......@@ -85,8 +93,6 @@ BadHeaderError: Header values can't contain newlines (got u'Subject\nInjection T
>>> mail_managers('hi','there')
>>> len(mail.outbox)
1
>>> settings.ADMINS = old_admins
>>> settings.MANAGERS = old_managers
# Make sure we can manually set the From header (#9214)
......@@ -138,4 +144,217 @@ Content-Disposition: attachment; filename="an attachment.pdf"
JVBERi0xLjQuJS4uLg==
...
# Make sure that the console backend writes to stdout by default
>>> connection = console.EmailBackend()
>>> email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
>>> connection.send_messages([email])
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Subject: Subject
From: from@example.com
To: to@example.com
Date: ...
Message-ID: ...
Content
-------------------------------------------------------------------------------
1
# Test that the console backend can be pointed at an arbitrary stream
>>> s = StringIO()
>>> connection = mail.get_connection('django.core.mail.backends.console', stream=s)
>>> send_mail('Subject', 'Content', 'from@example.com', ['to@example.com'], connection=connection)
1
>>> print s.getvalue()
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Subject: Subject
From: from@example.com
To: to@example.com
Date: ...
Message-ID: ...
Content
-------------------------------------------------------------------------------
# Make sure that dummy backends returns correct number of sent messages
>>> connection = dummy.EmailBackend()
>>> email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
>>> connection.send_messages([email, email, email])
3
# Make sure that locmen backend populates the outbox
>>> mail.outbox = []
>>> connection = locmem.EmailBackend()
>>> email1 = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
>>> email2 = EmailMessage('Subject 2', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
>>> connection.send_messages([email1, email2])
2
>>> len(mail.outbox)
2
>>> mail.outbox[0].subject
'Subject'
>>> mail.outbox[1].subject
'Subject 2'
# Make sure that multiple locmem connections share mail.outbox
>>> mail.outbox = []
>>> connection1 = locmem.EmailBackend()
>>> connection2 = locmem.EmailBackend()
>>> email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
>>> connection1.send_messages([email])
1
>>> connection2.send_messages([email])
1
>>> len(mail.outbox)
2
# Make sure that the file backend write to the right location
>>> tmp_dir = tempfile.mkdtemp()
>>> connection = filebased.EmailBackend(file_path=tmp_dir)
>>> email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
>>> connection.send_messages([email])
1
>>> len(os.listdir(tmp_dir))
1
>>> print open(os.path.join(tmp_dir, os.listdir(tmp_dir)[0])).read()
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Subject: Subject
From: from@example.com
To: to@example.com
Date: ...
Message-ID: ...
Content
-------------------------------------------------------------------------------
>>> connection2 = filebased.EmailBackend(file_path=tmp_dir)
>>> connection2.send_messages([email])
1
>>> len(os.listdir(tmp_dir))
2
>>> connection.send_messages([email])
1
>>> len(os.listdir(tmp_dir))
2
>>> email.connection = filebased.EmailBackend(file_path=tmp_dir)
>>> connection_created = connection.open()
>>> num_sent = email.send()
>>> len(os.listdir(tmp_dir))
3
>>> num_sent = email.send()
>>> len(os.listdir(tmp_dir))
3
>>> connection.close()
>>> shutil.rmtree(tmp_dir)
# Make sure that get_connection() accepts arbitrary keyword that might be
# used with custom backends.
>>> c = mail.get_connection(fail_silently=True, foo='bar')
>>> c.fail_silently
True
# Test custom backend defined in this suite.
>>> conn = mail.get_connection('regressiontests.mail.custombackend')
>>> hasattr(conn, 'test_outbox')
True
>>> email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
>>> conn.send_messages([email])
1
>>> len(conn.test_outbox)
1
# Test backend argument of mail.get_connection()
>>> isinstance(mail.get_connection('django.core.mail.backends.smtp'), smtp.EmailBackend)
True
>>> isinstance(mail.get_connection('django.core.mail.backends.locmem'), locmem.EmailBackend)
True
>>> isinstance(mail.get_connection('django.core.mail.backends.dummy'), dummy.EmailBackend)
True
>>> isinstance(mail.get_connection('django.core.mail.backends.console'), console.EmailBackend)
True
>>> tmp_dir = tempfile.mkdtemp()
>>> isinstance(mail.get_connection('django.core.mail.backends.filebased', file_path=tmp_dir), filebased.EmailBackend)
True
>>> shutil.rmtree(tmp_dir)
>>> isinstance(mail.get_connection(), locmem.EmailBackend)
True
# Test connection argument of send_mail() et al
>>> connection = mail.get_connection('django.core.mail.backends.console')
>>> send_mail('Subject', 'Content', 'from@example.com', ['to@example.com'], connection=connection)
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Subject: Subject
From: from@example.com
To: to@example.com
Date: ...
Message-ID: ...
Content
-------------------------------------------------------------------------------
1
>>> send_mass_mail([
... ('Subject1', 'Content1', 'from1@example.com', ['to1@example.com']),
... ('Subject2', 'Content2', 'from2@example.com', ['to2@example.com'])
... ], connection=connection)
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Subject: Subject1
From: from1@example.com
To: to1@example.com
Date: ...
Message-ID: ...
Content1
-------------------------------------------------------------------------------
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Subject: Subject2
From: from2@example.com
To: to2@example.com
Date: ...
Message-ID: ...
Content2
-------------------------------------------------------------------------------
2
>>> mail_admins('Subject', 'Content', connection=connection)
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Subject: [Django] Subject
From: root@localhost
To: nobody@example.com
Date: ...
Message-ID: ...
Content
-------------------------------------------------------------------------------
>>> mail_managers('Subject', 'Content', connection=connection)
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Subject: [Django] Subject
From: root@localhost
To: nobody@example.com
Date: ...
Message-ID: ...
Content
-------------------------------------------------------------------------------
>>> settings.ADMINS = old_admins
>>> settings.MANAGERS = old_managers
"""
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment