单独调用 send_mail 函数会由于主题中的换行而导致 BadHeaderError 异常。
我希望这个 test_newline_causes_exception 也会失败,但事实并非如此。这是在 Django 1.3 中。有任何想法吗?
from django.core.mail import send_mail
from django.utils import unittest
class EmailTestCase(unittest.TestCase):
def test_newline_causes_exception(self):
send_mail('Header\nInjection', 'Here is the message.', 'from@example.com',
['to@example.com'], fail_silently=False)
编辑:这个新测试表明,在测试中使用 send_mail 时,不会调用标头检查代码 (django.core.mail.message.forbid_multi_line_headers)。
from django.core.mail import send_mail, BadHeaderError, outbox
from django.utils import unittest
class EmailTestCase(unittest.TestCase):
def test_newline_in_subject_should_raise_exception(self):
try:
send_mail('Subject\nhere', 'Here is the message.',
'from@example.com', ['to@example.com'], fail_silently=False)
except BadHeaderError:
raise Exception
self.assertEqual(len(outbox), 1)
self.assertEqual(outbox[0].subject, 'Subject here')
结果:
AssertionError: 'Subject\nhere' != 'Subject here'