[1.2.X] Fixed #14440 - Converted mail doctests to unittests.

Thanks to Rob Hudson for the patch and also to andialbrecht who filed a
similar patch that I didn't use.

Backport of r14143 from trunk.

git-svn-id: http://code.djangoproject.com/svn/django/branches/releases/1.2.X@14144 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Jacob Kaplan-Moss 2010-10-11 15:18:34 +00:00
parent 1534af4b44
commit 69d40b4a6f

View File

@ -1,420 +1,318 @@
# coding: utf-8 # coding: utf-8
import email
import os
import shutil
import sys
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.core.mail.message import BadHeaderError
from django.test import TestCase
from django.utils.translation import ugettext_lazy
r""" class MailTests(TestCase):
# Tests for the django.core.mail.
>>> import os def test_ascii(self):
>>> import shutil email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com'])
>>> import tempfile message = email.message()
>>> from StringIO import StringIO self.assertEqual(message['Subject'].encode(), 'Subject')
>>> from django.conf import settings self.assertEqual(message.get_payload(), 'Content')
>>> from django.core import mail self.assertEqual(message['From'], 'from@example.com')
>>> from django.core.mail import EmailMessage, mail_admins, mail_managers, EmailMultiAlternatives self.assertEqual(message['To'], 'to@example.com')
>>> 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: def test_multiple_recipients(self):
email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com','other@example.com'])
message = email.message()
self.assertEqual(message['Subject'].encode(), 'Subject')
self.assertEqual(message.get_payload(), 'Content')
self.assertEqual(message['From'], 'from@example.com')
self.assertEqual(message['To'], 'to@example.com, other@example.com')
>>> email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com']) def test_header_injection(self):
>>> message = email.message() email = EmailMessage('Subject\nInjection Test', 'Content', 'from@example.com', ['to@example.com'])
>>> message['Subject'].encode() self.assertRaises(BadHeaderError, email.message)
'Subject' email = EmailMessage(ugettext_lazy('Subject\nInjection Test'), 'Content', 'from@example.com', ['to@example.com'])
>>> message.get_payload() self.assertRaises(BadHeaderError, email.message)
'Content'
>>> message['From']
'from@example.com'
>>> message['To']
'to@example.com'
# Test multiple-recipient case def test_space_continuation(self):
"""
Test for space continuation character in long (ascii) subject headers (#7747)
"""
email = EmailMessage('Long subject lines that get wrapped should use a space continuation character to get expected behaviour in Outlook and Thunderbird', 'Content', 'from@example.com', ['to@example.com'])
message = email.message()
self.assertEqual(message['Subject'], 'Long subject lines that get wrapped should use a space continuation\n character to get expected behaviour in Outlook and Thunderbird')
>>> email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com','other@example.com']) def test_message_header_overrides(self):
>>> message = email.message() """
>>> message['Subject'].encode() Specifying dates or message-ids in the extra headers overrides the
'Subject' default values (#9233)
>>> message.get_payload() """
'Content' headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
>>> message['From'] email = EmailMessage('subject', 'content', 'from@example.com', ['to@example.com'], headers=headers)
'from@example.com' self.assertEqual(email.message().as_string(), 'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: subject\nFrom: from@example.com\nTo: to@example.com\ndate: Fri, 09 Nov 2001 01:08:47 -0000\nMessage-ID: foo\n\ncontent')
>>> message['To']
'to@example.com, other@example.com'
# Test for header injection def test_empty_admins(self):
"""
Test that mail_admins/mail_managers doesn't connect to the mail server
if there are no recipients (#9383)
"""
old_admins = settings.ADMINS
old_managers = settings.MANAGERS
>>> email = EmailMessage('Subject\nInjection Test', 'Content', 'from@example.com', ['to@example.com']) settings.ADMINS = settings.MANAGERS = [('nobody','nobody@example.com')]
>>> message = email.message() mail.outbox = []
Traceback (most recent call last): mail_admins('hi', 'there')
... self.assertEqual(len(mail.outbox), 1)
BadHeaderError: Header values can't contain newlines (got u'Subject\nInjection Test' for header 'Subject') mail.outbox = []
mail_managers('hi', 'there')
self.assertEqual(len(mail.outbox), 1)
>>> email = EmailMessage(ugettext_lazy('Subject\nInjection Test'), 'Content', 'from@example.com', ['to@example.com']) settings.ADMINS = settings.MANAGERS = []
>>> message = email.message() mail.outbox = []
Traceback (most recent call last): mail_admins('hi', 'there')
... self.assertEqual(len(mail.outbox), 0)
BadHeaderError: Header values can't contain newlines (got u'Subject\nInjection Test' for header 'Subject') mail.outbox = []
mail_managers('hi', 'there')
self.assertEqual(len(mail.outbox), 0)
# Test for space continuation character in long (ascii) subject headers (#7747) settings.ADMINS = old_admins
settings.MANAGERS = old_managers
>>> email = EmailMessage('Long subject lines that get wrapped should use a space continuation character to get expected behaviour in Outlook and Thunderbird', 'Content', 'from@example.com', ['to@example.com']) def test_from_header(self):
>>> message = email.message() """
>>> message.as_string() Make sure we can manually set the From header (#9214)
'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Long subject lines that get wrapped should use a space continuation\n character to get expected behaviour in Outlook and Thunderbird\nFrom: from@example.com\nTo: to@example.com\nDate: ...\nMessage-ID: <...>\n\nContent' """
email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
message = email.message()
self.assertEqual(message['From'], 'from@example.com')
# Specifying dates or message-ids in the extra headers overrides the defaul def test_multiple_message_call(self):
# values (#9233). """
Regression for #13259 - Make sure that headers are not changed when
calling EmailMessage.message()
"""
email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
message = email.message()
self.assertEqual(message['From'], 'from@example.com')
message = email.message()
self.assertEqual(message['From'], 'from@example.com')
>>> headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} def test_unicode_header(self):
>>> email = EmailMessage('subject', 'content', 'from@example.com', ['to@example.com'], headers=headers) """
>>> email.message().as_string() Regression for #11144 - When a to/from/cc header contains unicode,
'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: subject\nFrom: from@example.com\nTo: to@example.com\ndate: Fri, 09 Nov 2001 01:08:47 -0000\nMessage-ID: foo\n\ncontent' make sure the email addresses are parsed correctly (especially with
regards to commas)
"""
email = EmailMessage('Subject', 'Content', 'from@example.com', ['"Firstname Sürname" <to@example.com>','other@example.com'])
self.assertEqual(email.message()['To'], '=?utf-8?q?Firstname_S=C3=BCrname?= <to@example.com>, other@example.com')
email = EmailMessage('Subject', 'Content', 'from@example.com', ['"Sürname, Firstname" <to@example.com>','other@example.com'])
self.assertEqual(email.message()['To'], '=?utf-8?q?S=C3=BCrname=2C_Firstname?= <to@example.com>, other@example.com')
# Test that mail_admins/mail_managers doesn't connect to the mail server if there are no recipients (#9383) def test_safe_mime_multipart(self):
"""
Make sure headers can be set with a different encoding than utf-8 in
SafeMIMEMultipart as well
"""
headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
subject, from_email, to = 'hello', 'from@example.com', '"Sürname, Firstname" <to@example.com>'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives('Message from Firstname Sürname', text_content, from_email, [to], headers=headers)
msg.attach_alternative(html_content, "text/html")
msg.encoding = 'iso-8859-1'
self.assertEqual(msg.message()['To'], '=?iso-8859-1?q?S=FCrname=2C_Firstname?= <to@example.com>')
self.assertEqual(msg.message()['Subject'].encode(), u'=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=')
>>> old_admins = settings.ADMINS def test_encoding(self):
>>> old_managers = settings.MANAGERS """
>>> settings.ADMINS = [] Regression for #12791 - Encode body correctly with other encodings
>>> settings.MANAGERS = [] than utf-8
>>> mail.outbox = [] """
>>> mail_admins('hi','there') email = EmailMessage('Subject', 'Firstname Sürname is a great guy.', 'from@example.com', ['other@example.com'])
>>> len(mail.outbox) email.encoding = 'iso-8859-1'
0 message = email.message()
>>> mail.outbox = [] self.assertTrue(message.as_string().startswith('Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: from@example.com\nTo: other@example.com'))
>>> mail_managers('hi','there') self.assertEqual(message.get_payload(), 'Firstname S=FCrname is a great guy.')
>>> len(mail.outbox)
0
>>> settings.ADMINS = settings.MANAGERS = [('nobody','nobody@example.com')]
>>> mail.outbox = []
>>> mail_admins('hi','there')
>>> len(mail.outbox)
1
>>> mail.outbox = []
>>> mail_managers('hi','there')
>>> len(mail.outbox)
1
# Make sure we can manually set the From header (#9214) # Make sure MIME attachments also works correctly with other encodings than utf-8
text_content = 'Firstname Sürname is a great guy.'
html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>'
msg = EmailMultiAlternatives('Subject', text_content, 'from@example.com', ['to@example.com'])
msg.encoding = 'iso-8859-1'
msg.attach_alternative(html_content, "text/html")
self.assertEqual(msg.message().get_payload(0).as_string(), 'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\nFirstname S=FCrname is a great guy.')
self.assertEqual(msg.message().get_payload(1).as_string(), 'Content-Type: text/html; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>')
>>> email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}) def test_attachments(self):
>>> message = email.message() """Regression test for #9367"""
>>> message['From'] headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
'from@example.com' subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
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], headers=headers)
msg.attach_alternative(html_content, "text/html")
msg.attach("an attachment.pdf", "%PDF-1.4.%...", mimetype="application/pdf")
msg_str = msg.message().as_string()
message = email.message_from_string(msg_str)
self.assertTrue(message.is_multipart())
self.assertEqual(message.get_content_type(), 'multipart/mixed')
self.assertEqual(message.get_default_type(), 'text/plain')
payload = message.get_payload()
self.assertEqual(payload[0].get_content_type(), 'multipart/alternative')
self.assertEqual(payload[1].get_content_type(), 'application/pdf')
# Regression for #13259 - Make sure that headers are not changed def test_arbitrary_stream(self):
# when calling EmailMessage.message() """
>>> email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}) Test that the console backend can be pointed at an arbitrary stream.
>>> message = email.message() """
>>> message['From'] s = StringIO()
'from@example.com' connection = mail.get_connection('django.core.mail.backends.console.EmailBackend', stream=s)
>>> message = email.message() send_mail('Subject', 'Content', 'from@example.com', ['to@example.com'], connection=connection)
>>> message['From'] self.assertTrue(s.getvalue().startswith('Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: from@example.com\nTo: to@example.com\nDate: '))
'from@example.com'
# Regression for #11144 - When a to/from/cc header contains unicode, def test_stdout(self):
# make sure the email addresses are parsed correctly (especially """Make sure that the console backend writes to stdout by default"""
# with regards to commas) old_stdout = sys.stdout
>>> email = EmailMessage('Subject', 'Content', 'from@example.com', ['"Firstname Sürname" <to@example.com>','other@example.com']) sys.stdout = StringIO()
>>> email.message()['To'] connection = console.EmailBackend()
'=?utf-8?q?Firstname_S=C3=BCrname?= <to@example.com>, other@example.com' email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
connection.send_messages([email])
self.assertTrue(sys.stdout.getvalue().startswith('Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: from@example.com\nTo: to@example.com\nDate: '))
sys.stdout = old_stdout
>>> email = EmailMessage('Subject', 'Content', 'from@example.com', ['"Sürname, Firstname" <to@example.com>','other@example.com']) def test_dummy(self):
>>> email.message()['To'] """
'=?utf-8?q?S=C3=BCrname=2C_Firstname?= <to@example.com>, other@example.com' 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'})
self.assertEqual(connection.send_messages([email, email, email]), 3)
# Regression for #6918 - When a header contains unicode, def test_locmem(self):
# make sure headers can be set with a different encoding than utf-8 """
>>> email = EmailMessage('Message from Firstname Sürname', 'Content', 'from@example.com', ['"Sürname, Firstname" <to@example.com>','other@example.com']) Make sure that the locmen backend populates the outbox.
>>> email.encoding = 'iso-8859-1' """
>>> email.message()['To'] mail.outbox = []
'=?iso-8859-1?q?S=FCrname=2C_Firstname?= <to@example.com>, other@example.com' connection = locmem.EmailBackend()
>>> email.message()['Subject'].encode() email1 = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
u'=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=' email2 = EmailMessage('Subject 2', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
connection.send_messages([email1, email2])
self.assertEqual(len(mail.outbox), 2)
self.assertEqual(mail.outbox[0].subject, 'Subject')
self.assertEqual(mail.outbox[1].subject, 'Subject 2')
# Make sure headers can be set with a different encoding than utf-8 in SafeMIMEMultipart as well # Make sure that multiple locmem connections share mail.outbox
>>> headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} mail.outbox = []
>>> subject, from_email, to = 'hello', 'from@example.com', '"Sürname, Firstname" <to@example.com>' connection2 = locmem.EmailBackend()
>>> text_content = 'This is an important message.' email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
>>> html_content = '<p>This is an <strong>important</strong> message.</p>' connection.send_messages([email])
>>> msg = EmailMultiAlternatives('Message from Firstname Sürname', text_content, from_email, [to], headers=headers) connection2.send_messages([email])
>>> msg.attach_alternative(html_content, "text/html") self.assertEqual(len(mail.outbox), 2)
>>> msg.encoding = 'iso-8859-1'
>>> msg.message()['To']
'=?iso-8859-1?q?S=FCrname=2C_Firstname?= <to@example.com>'
>>> msg.message()['Subject'].encode()
u'=?iso-8859-1?q?Message_from_Firstname_S=FCrname?='
# Regression for #12791 - Encode body correctly with other encodings than utf-8 def test_file_backend(self):
>>> email = EmailMessage('Subject', 'Firstname Sürname is a great guy.', 'from@example.com', ['other@example.com']) tmp_dir = tempfile.mkdtemp()
>>> email.encoding = 'iso-8859-1' connection = filebased.EmailBackend(file_path=tmp_dir)
>>> message = email.message() email1 = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
>>> message.as_string() connection.send_messages([email1])
'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: from@example.com\nTo: other@example.com\nDate: ...\nMessage-ID: <...>\n\nFirstname S=FCrname is a great guy.' self.assertEqual(len(os.listdir(tmp_dir)), 1)
message = email.message_from_file(open(os.path.join(tmp_dir, os.listdir(tmp_dir)[0])))
self.assertEqual(message.get_content_type(), 'text/plain')
self.assertEqual(message.get('subject'), 'Subject')
self.assertEqual(message.get('from'), 'from@example.com')
self.assertEqual(message.get('to'), 'to@example.com')
connection2 = filebased.EmailBackend(file_path=tmp_dir)
connection2.send_messages([email1])
self.assertEqual(len(os.listdir(tmp_dir)), 2)
connection.send_messages([email1])
self.assertEqual(len(os.listdir(tmp_dir)), 2)
email1.connection = filebased.EmailBackend(file_path=tmp_dir)
connection_created = connection.open()
email1.send()
self.assertEqual(len(os.listdir(tmp_dir)), 3)
email1.send()
self.assertEqual(len(os.listdir(tmp_dir)), 3)
connection.close()
shutil.rmtree(tmp_dir)
# Make sure MIME attachments also works correctly with other encodings than utf-8 def test_arbitrary_keyword(self):
>>> text_content = 'Firstname Sürname is a great guy.' """
>>> html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>' Make sure that get_connection() accepts arbitrary keyword that might be
>>> msg = EmailMultiAlternatives('Subject', text_content, 'from@example.com', ['to@example.com']) used with custom backends.
>>> msg.encoding = 'iso-8859-1' """
>>> msg.attach_alternative(html_content, "text/html") c = mail.get_connection(fail_silently=True, foo='bar')
>>> msg.message().get_payload(0).as_string() self.assertTrue(c.fail_silently)
'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\nFirstname S=FCrname is a great guy.'
>>> msg.message().get_payload(1).as_string()
'Content-Type: text/html; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>'
# Handle attachments within an multipart/alternative mail correctly (#9367) def test_custom_backend(self):
# (test is not as precise/clear as it could be w.r.t. email tree structure, """Test custom backend defined in this suite."""
# but it's good enough.) conn = mail.get_connection('regressiontests.mail.custombackend.EmailBackend')
>>> headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} self.assertTrue(hasattr(conn, 'test_outbox'))
>>> subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
>>> text_content = 'This is an important message.' conn.send_messages([email])
>>> html_content = '<p>This is an <strong>important</strong> message.</p>' self.assertEqual(len(conn.test_outbox), 1)
>>> msg = EmailMultiAlternatives(subject, text_content, from_email, [to], headers=headers)
>>> msg.attach_alternative(html_content, "text/html")
>>> msg.attach("an attachment.pdf", "%PDF-1.4.%...", mimetype="application/pdf")
>>> print msg.message().as_string()
Content-Type: multipart/mixed; boundary="..."
MIME-Version: 1.0
Subject: hello
From: from@example.com
To: to@example.com
Date: Fri, 09 Nov 2001 01:08:47 -0000
Message-ID: foo
...
Content-Type: multipart/alternative;...
...
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
...
This is an important message.
...
Content-Type: text/html; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
...
<p>This is an <strong>important</strong> message.</p>
...
...
Content-Type: application/pdf
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="an attachment.pdf"
...
JVBERi0xLjQuJS4uLg==
...
# Make sure that the console backend writes to stdout by default def test_backend_arg(self):
>>> connection = console.EmailBackend() """Test backend argument of mail.get_connection()"""
>>> email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}) self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.smtp.EmailBackend'), smtp.EmailBackend))
>>> connection.send_messages([email]) self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.locmem.EmailBackend'), locmem.EmailBackend))
Content-Type: text/plain; charset="utf-8" self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.dummy.EmailBackend'), dummy.EmailBackend))
MIME-Version: 1.0 self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.console.EmailBackend'), console.EmailBackend))
Content-Transfer-Encoding: quoted-printable tmp_dir = tempfile.mkdtemp()
Subject: Subject self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.filebased.EmailBackend', file_path=tmp_dir), filebased.EmailBackend))
From: from@example.com shutil.rmtree(tmp_dir)
To: to@example.com self.assertTrue(isinstance(mail.get_connection(), locmem.EmailBackend))
Date: ...
Message-ID: ...
Content def test_connection_arg(self):
------------------------------------------------------------------------------- """Test connection argument to send_mail(), et. al."""
1 connection = mail.get_connection('django.core.mail.backends.locmem.EmailBackend')
# Test that the console backend can be pointed at an arbitrary stream mail.outbox = []
>>> s = StringIO() send_mail('Subject', 'Content', 'from@example.com', ['to@example.com'], connection=connection)
>>> connection = mail.get_connection('django.core.mail.backends.console.EmailBackend', stream=s) self.assertEqual(len(mail.outbox), 1)
>>> send_mail('Subject', 'Content', 'from@example.com', ['to@example.com'], connection=connection) message = mail.outbox[0]
1 self.assertEqual(message.subject, 'Subject')
>>> print s.getvalue() self.assertEqual(message.from_email, 'from@example.com')
Content-Type: text/plain; charset="utf-8" self.assertEqual(message.to, ['to@example.com'])
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Subject: Subject
From: from@example.com
To: to@example.com
Date: ...
Message-ID: ...
Content mail.outbox = []
------------------------------------------------------------------------------- send_mass_mail([
('Subject1', 'Content1', 'from1@example.com', ['to1@example.com']),
('Subject2', 'Content2', 'from2@example.com', ['to2@example.com'])
], connection=connection)
self.assertEqual(len(mail.outbox), 2)
message = mail.outbox[0]
self.assertEqual(message.subject, 'Subject1')
self.assertEqual(message.from_email, 'from1@example.com')
self.assertEqual(message.to, ['to1@example.com'])
message = mail.outbox[1]
self.assertEqual(message.subject, 'Subject2')
self.assertEqual(message.from_email, 'from2@example.com')
self.assertEqual(message.to, ['to2@example.com'])
# Make sure that dummy backends returns correct number of sent messages old_admins = settings.ADMINS
>>> connection = dummy.EmailBackend() old_managers = settings.MANAGERS
>>> email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}) settings.ADMINS = settings.MANAGERS = [('nobody','nobody@example.com')]
>>> connection.send_messages([email, email, email])
3
# Make sure that locmen backend populates the outbox mail.outbox = []
>>> mail.outbox = [] mail_admins('Subject', 'Content', connection=connection)
>>> connection = locmem.EmailBackend() self.assertEqual(len(mail.outbox), 1)
>>> email1 = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}) message = mail.outbox[0]
>>> email2 = EmailMessage('Subject 2', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}) self.assertEqual(message.subject, '[Django] Subject')
>>> connection.send_messages([email1, email2]) self.assertEqual(message.from_email, 'root@localhost')
2 self.assertEqual(message.to, ['nobody@example.com'])
>>> 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 = []
>>> mail.outbox = [] mail_managers('Subject', 'Content', connection=connection)
>>> connection1 = locmem.EmailBackend() self.assertEqual(len(mail.outbox), 1)
>>> connection2 = locmem.EmailBackend() message = mail.outbox[0]
>>> email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}) self.assertEqual(message.subject, '[Django] Subject')
>>> connection1.send_messages([email]) self.assertEqual(message.from_email, 'root@localhost')
1 self.assertEqual(message.to, ['nobody@example.com'])
>>> connection2.send_messages([email])
1
>>> len(mail.outbox)
2
# Make sure that the file backend write to the right location settings.ADMINS = old_admins
>>> tmp_dir = tempfile.mkdtemp() settings.MANAGERS = old_managers
>>> 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.EmailBackend')
>>> 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.EmailBackend'), smtp.EmailBackend)
True
>>> isinstance(mail.get_connection('django.core.mail.backends.locmem.EmailBackend'), locmem.EmailBackend)
True
>>> isinstance(mail.get_connection('django.core.mail.backends.dummy.EmailBackend'), dummy.EmailBackend)
True
>>> isinstance(mail.get_connection('django.core.mail.backends.console.EmailBackend'), console.EmailBackend)
True
>>> tmp_dir = tempfile.mkdtemp()
>>> isinstance(mail.get_connection('django.core.mail.backends.filebased.EmailBackend', 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.EmailBackend')
>>> 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
"""