diff --git a/django/core/mail.py b/django/core/mail.py index b60757366f..78a1ec6192 100644 --- a/django/core/mail.py +++ b/django/core/mail.py @@ -71,10 +71,11 @@ class BadHeaderError(ValueError): def forbid_multi_line_headers(name, val): """Forbids multi-line headers, to prevent header injection.""" + val = force_unicode(val) if '\n' in val or '\r' in val: raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name)) try: - val = force_unicode(val).encode('ascii') + val = val.encode('ascii') except UnicodeEncodeError: if name.lower() in ('to', 'from', 'cc'): result = [] @@ -84,7 +85,7 @@ def forbid_multi_line_headers(name, val): result.append(formataddr((nm, str(addr)))) val = ', '.join(result) else: - val = Header(force_unicode(val), settings.DEFAULT_CHARSET) + val = Header(val, settings.DEFAULT_CHARSET) return name, val class SafeMIMEText(MIMEText): diff --git a/tests/regressiontests/mail/tests.py b/tests/regressiontests/mail/tests.py index 9d2e2abe96..be59234342 100644 --- a/tests/regressiontests/mail/tests.py +++ b/tests/regressiontests/mail/tests.py @@ -3,6 +3,7 @@ r""" # Tests for the django.core.mail. >>> from django.core.mail import EmailMessage +>>> from django.utils.translation import ugettext_lazy # Test normal ascii character case: @@ -36,6 +37,12 @@ r""" >>> message = email.message() Traceback (most recent call last): ... -BadHeaderError: Header values can't contain newlines (got 'Subject\nInjection Test' for header 'Subject') +BadHeaderError: Header values can't contain newlines (got u'Subject\nInjection Test' for header 'Subject') + +>>> email = EmailMessage(ugettext_lazy('Subject\nInjection Test'), 'Content', 'from@example.com', ['to@example.com']) +>>> message = email.message() +Traceback (most recent call last): + ... +BadHeaderError: Header values can't contain newlines (got u'Subject\nInjection Test' for header 'Subject') """