mirror of
https://github.com/django/django.git
synced 2025-07-04 09:49:12 +00:00
unicode: Added support for sending email that contains unicode data. Refs #3398.
git-svn-id: http://code.djangoproject.com/svn/django/branches/unicode@5282 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
e10da26109
commit
68a0f4f51b
@ -3,9 +3,10 @@ Tools for sending email.
|
||||
"""
|
||||
|
||||
from django.conf import settings
|
||||
from django.utils.encoding import smart_str, smart_unicode
|
||||
from email.MIMEText import MIMEText
|
||||
from email.Header import Header
|
||||
from email.Utils import formatdate
|
||||
from email.Utils import formatdate, parseaddr, formataddr
|
||||
from email import Charset
|
||||
import os
|
||||
import smtplib
|
||||
@ -60,8 +61,18 @@ class SafeMIMEText(MIMEText):
|
||||
"Forbids multi-line headers, to prevent header injection."
|
||||
if '\n' in val or '\r' in val:
|
||||
raise BadHeaderError, "Header values can't contain newlines (got %r for header %r)" % (val, name)
|
||||
if name == "Subject":
|
||||
val = Header(val, settings.DEFAULT_CHARSET)
|
||||
try:
|
||||
val = str(smart_unicode(val))
|
||||
except UnicodeEncodeError:
|
||||
if name.lower() in ('to', 'from', 'cc'):
|
||||
result = []
|
||||
for item in val.split(', '):
|
||||
nm, addr = parseaddr(item)
|
||||
nm = str(Header(nm, settings.DEFAULT_CHARSET))
|
||||
result.append(formataddr((nm, str(addr))))
|
||||
val = ', '.join(result)
|
||||
else:
|
||||
val = Header(smart_unicode(val), settings.DEFAULT_CHARSET)
|
||||
MIMEText.__setitem__(self, name, val)
|
||||
|
||||
class SMTPConnection(object):
|
||||
@ -155,6 +166,14 @@ class EmailMessage(object):
|
||||
A container for email information.
|
||||
"""
|
||||
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None):
|
||||
"""
|
||||
Initialise 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.
|
||||
"""
|
||||
self.to = to or []
|
||||
self.bcc = bcc or []
|
||||
self.from_email = from_email or settings.DEFAULT_FROM_EMAIL
|
||||
@ -168,7 +187,7 @@ class EmailMessage(object):
|
||||
return self.connection
|
||||
|
||||
def message(self):
|
||||
msg = SafeMIMEText(self.body, 'plain', settings.DEFAULT_CHARSET)
|
||||
msg = SafeMIMEText(smart_str(self.body, settings.DEFAULT_CHARSET), 'plain', settings.DEFAULT_CHARSET)
|
||||
msg['Subject'] = self.subject
|
||||
msg['From'] = self.from_email
|
||||
msg['To'] = ', '.join(self.to)
|
||||
|
Loading…
x
Reference in New Issue
Block a user