2007-06-27 17:44:55 +08:00
|
|
|
import mimetypes
|
2007-05-03 19:35:11 +08:00
|
|
|
import os
|
2006-11-07 23:32:18 +08:00
|
|
|
import random
|
2009-11-03 20:53:26 +08:00
|
|
|
import time
|
2008-03-22 05:52:34 +08:00
|
|
|
from email import Charset, Encoders
|
|
|
|
from email.MIMEText import MIMEText
|
|
|
|
from email.MIMEMultipart import MIMEMultipart
|
|
|
|
from email.MIMEBase import MIMEBase
|
|
|
|
from email.Header import Header
|
2009-11-04 19:24:56 +08:00
|
|
|
from email.Utils import formatdate, getaddresses, formataddr
|
2008-03-22 05:52:34 +08:00
|
|
|
|
|
|
|
from django.conf import settings
|
2009-11-03 20:53:26 +08:00
|
|
|
from django.core.mail.utils import DNS_NAME
|
2008-03-22 05:52:34 +08:00
|
|
|
from django.utils.encoding import smart_str, force_unicode
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2007-05-03 20:08:31 +08:00
|
|
|
# Don't BASE64-encode UTF-8 messages so that we avoid unwanted attention from
|
|
|
|
# some spam filters.
|
|
|
|
Charset.add_charset('utf-8', Charset.SHORTEST, Charset.QP, 'utf-8')
|
|
|
|
|
2007-06-27 17:44:55 +08:00
|
|
|
# Default MIME type to use on attachments (if it is not explicitly given
|
|
|
|
# and cannot be guessed).
|
|
|
|
DEFAULT_ATTACHMENT_MIME_TYPE = 'application/octet-stream'
|
|
|
|
|
2007-02-17 14:01:17 +08:00
|
|
|
|
2009-11-03 20:53:26 +08:00
|
|
|
class BadHeaderError(ValueError):
|
|
|
|
pass
|
2007-02-17 14:01:17 +08:00
|
|
|
|
2006-11-10 11:28:58 +08:00
|
|
|
|
2008-03-22 05:39:50 +08:00
|
|
|
# Copied from Python standard library, with the following modifications:
|
|
|
|
# * Used cached hostname for performance.
|
|
|
|
# * Added try/except to support lack of getpid() in Jython (#5496).
|
2007-05-03 19:35:11 +08:00
|
|
|
def make_msgid(idstring=None):
|
|
|
|
"""Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
|
|
|
|
|
|
|
|
<20020201195627.33539.96671@nightshade.la.mastaler.com>
|
|
|
|
|
|
|
|
Optional idstring if given is a string used to strengthen the
|
|
|
|
uniqueness of the message id.
|
|
|
|
"""
|
|
|
|
timeval = time.time()
|
|
|
|
utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
|
2007-09-15 17:51:41 +08:00
|
|
|
try:
|
|
|
|
pid = os.getpid()
|
|
|
|
except AttributeError:
|
2008-03-22 05:39:50 +08:00
|
|
|
# No getpid() in Jython, for example.
|
2007-09-15 17:51:41 +08:00
|
|
|
pid = 1
|
2007-05-03 19:35:11 +08:00
|
|
|
randint = random.randrange(100000)
|
|
|
|
if idstring is None:
|
|
|
|
idstring = ''
|
|
|
|
else:
|
|
|
|
idstring = '.' + idstring
|
|
|
|
idhost = DNS_NAME
|
|
|
|
msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
|
|
|
|
return msgid
|
|
|
|
|
2005-12-30 06:12:54 +08:00
|
|
|
|
2010-03-06 05:27:58 +08:00
|
|
|
def forbid_multi_line_headers(name, val, encoding):
|
2008-03-22 05:52:34 +08:00
|
|
|
"""Forbids multi-line headers, to prevent header injection."""
|
2010-03-06 23:50:12 +08:00
|
|
|
encoding = encoding or settings.DEFAULT_CHARSET
|
2008-07-26 11:37:25 +08:00
|
|
|
val = force_unicode(val)
|
2008-01-02 16:39:03 +08:00
|
|
|
if '\n' in val or '\r' in val:
|
|
|
|
raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name))
|
|
|
|
try:
|
2008-07-26 11:37:25 +08:00
|
|
|
val = val.encode('ascii')
|
2008-01-02 16:39:03 +08:00
|
|
|
except UnicodeEncodeError:
|
|
|
|
if name.lower() in ('to', 'from', 'cc'):
|
|
|
|
result = []
|
2009-11-04 19:24:56 +08:00
|
|
|
for nm, addr in getaddresses((val,)):
|
2010-03-06 05:27:58 +08:00
|
|
|
nm = str(Header(nm.encode(encoding), encoding))
|
2008-01-02 16:39:03 +08:00
|
|
|
result.append(formataddr((nm, str(addr))))
|
|
|
|
val = ', '.join(result)
|
|
|
|
else:
|
2010-03-06 05:27:58 +08:00
|
|
|
val = Header(val.encode(encoding), encoding)
|
2008-08-23 21:31:28 +08:00
|
|
|
else:
|
|
|
|
if name.lower() == 'subject':
|
|
|
|
val = Header(val)
|
2008-01-02 16:39:03 +08:00
|
|
|
return name, val
|
2008-01-02 13:29:10 +08:00
|
|
|
|
|
|
|
class SafeMIMEText(MIMEText):
|
2010-03-06 05:27:58 +08:00
|
|
|
|
|
|
|
def __init__(self, text, subtype, charset):
|
|
|
|
self.encoding = charset
|
|
|
|
MIMEText.__init__(self, text, subtype, charset)
|
|
|
|
|
|
|
|
def __setitem__(self, name, val):
|
|
|
|
name, val = forbid_multi_line_headers(name, val, self.encoding)
|
2007-07-01 14:32:34 +08:00
|
|
|
MIMEText.__setitem__(self, name, val)
|
2007-06-27 17:44:55 +08:00
|
|
|
|
2007-07-01 14:32:34 +08:00
|
|
|
class SafeMIMEMultipart(MIMEMultipart):
|
2010-03-06 05:27:58 +08:00
|
|
|
|
|
|
|
def __init__(self, _subtype='mixed', boundary=None, _subparts=None, encoding=None, **_params):
|
|
|
|
self.encoding = encoding
|
|
|
|
MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params)
|
|
|
|
|
2007-07-01 14:32:34 +08:00
|
|
|
def __setitem__(self, name, val):
|
2010-03-06 05:27:58 +08:00
|
|
|
name, val = forbid_multi_line_headers(name, val, self.encoding)
|
2007-07-01 14:32:34 +08:00
|
|
|
MIMEMultipart.__setitem__(self, name, val)
|
2005-12-30 04:33:56 +08:00
|
|
|
|
2007-05-03 19:35:11 +08:00
|
|
|
class EmailMessage(object):
|
|
|
|
"""
|
|
|
|
A container for email information.
|
|
|
|
"""
|
2007-06-27 20:18:05 +08:00
|
|
|
content_subtype = 'plain'
|
2009-06-12 21:56:40 +08:00
|
|
|
mixed_subtype = 'mixed'
|
2007-06-27 20:54:15 +08:00
|
|
|
encoding = None # None => use settings default
|
2007-06-27 20:18:05 +08:00
|
|
|
|
2007-06-27 17:44:55 +08:00
|
|
|
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
|
2009-11-03 20:53:26 +08:00
|
|
|
connection=None, attachments=None, headers=None):
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
"""
|
2008-03-22 05:52:34 +08:00
|
|
|
Initialize a single email message (which can be sent to multiple
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
recipients).
|
|
|
|
|
2009-11-03 20:53:26 +08:00
|
|
|
All strings used to create the message can be unicode strings
|
|
|
|
(or UTF-8 bytestrings). The SafeMIMEText class will handle any
|
|
|
|
necessary encoding conversions.
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
"""
|
2007-12-19 12:51:35 +08:00
|
|
|
if to:
|
2008-07-08 09:56:01 +08:00
|
|
|
assert not isinstance(to, basestring), '"to" argument must be a list or tuple'
|
2007-12-19 12:51:35 +08:00
|
|
|
self.to = list(to)
|
|
|
|
else:
|
|
|
|
self.to = []
|
|
|
|
if bcc:
|
2008-07-08 09:56:01 +08:00
|
|
|
assert not isinstance(bcc, basestring), '"bcc" argument must be a list or tuple'
|
2007-12-19 12:51:35 +08:00
|
|
|
self.bcc = list(bcc)
|
|
|
|
else:
|
|
|
|
self.bcc = []
|
2007-05-03 22:38:45 +08:00
|
|
|
self.from_email = from_email or settings.DEFAULT_FROM_EMAIL
|
2007-05-03 19:35:11 +08:00
|
|
|
self.subject = subject
|
|
|
|
self.body = body
|
2007-06-27 17:44:55 +08:00
|
|
|
self.attachments = attachments or []
|
2007-06-27 20:41:37 +08:00
|
|
|
self.extra_headers = headers or {}
|
2007-05-03 19:35:11 +08:00
|
|
|
self.connection = connection
|
|
|
|
|
|
|
|
def get_connection(self, fail_silently=False):
|
2009-11-03 20:53:26 +08:00
|
|
|
from django.core.mail import get_connection
|
2007-05-03 19:35:11 +08:00
|
|
|
if not self.connection:
|
2009-11-03 20:53:26 +08:00
|
|
|
self.connection = get_connection(fail_silently=fail_silently)
|
2007-05-03 19:35:11 +08:00
|
|
|
return self.connection
|
|
|
|
|
|
|
|
def message(self):
|
2007-06-27 20:54:15 +08:00
|
|
|
encoding = self.encoding or settings.DEFAULT_CHARSET
|
2010-03-06 05:27:58 +08:00
|
|
|
msg = SafeMIMEText(smart_str(self.body, encoding),
|
2008-03-22 05:52:34 +08:00
|
|
|
self.content_subtype, encoding)
|
2009-06-12 21:56:40 +08:00
|
|
|
msg = self._create_message(msg)
|
2007-05-03 19:35:11 +08:00
|
|
|
msg['Subject'] = self.subject
|
2010-04-01 23:16:26 +08:00
|
|
|
msg['From'] = self.extra_headers.get('From', self.from_email)
|
2007-05-03 19:35:11 +08:00
|
|
|
msg['To'] = ', '.join(self.to)
|
2008-10-07 20:20:01 +08:00
|
|
|
|
|
|
|
# Email header names are case-insensitive (RFC 2045), so we have to
|
|
|
|
# accommodate that when doing comparisons.
|
|
|
|
header_names = [key.lower() for key in self.extra_headers]
|
|
|
|
if 'date' not in header_names:
|
|
|
|
msg['Date'] = formatdate()
|
|
|
|
if 'message-id' not in header_names:
|
|
|
|
msg['Message-ID'] = make_msgid()
|
2007-06-27 20:41:37 +08:00
|
|
|
for name, value in self.extra_headers.items():
|
2010-04-01 23:16:26 +08:00
|
|
|
if name.lower() == 'from': # From is already handled
|
|
|
|
continue
|
2007-06-27 20:41:37 +08:00
|
|
|
msg[name] = value
|
2007-05-03 19:50:43 +08:00
|
|
|
return msg
|
2007-05-03 19:35:11 +08:00
|
|
|
|
2007-05-03 22:38:45 +08:00
|
|
|
def recipients(self):
|
|
|
|
"""
|
|
|
|
Returns a list of all recipients of the email (includes direct
|
|
|
|
addressees as well as Bcc entries).
|
|
|
|
"""
|
|
|
|
return self.to + self.bcc
|
|
|
|
|
2007-05-03 19:35:11 +08:00
|
|
|
def send(self, fail_silently=False):
|
2008-03-22 05:52:34 +08:00
|
|
|
"""Sends the email message."""
|
2008-10-24 12:38:43 +08:00
|
|
|
if not self.recipients():
|
|
|
|
# Don't bother creating the network connection if there's nobody to
|
|
|
|
# send to.
|
|
|
|
return 0
|
2007-05-03 19:35:11 +08:00
|
|
|
return self.get_connection(fail_silently).send_messages([self])
|
|
|
|
|
2007-06-27 20:18:05 +08:00
|
|
|
def attach(self, filename=None, content=None, mimetype=None):
|
2007-06-27 17:44:55 +08:00
|
|
|
"""
|
2007-06-27 20:18:05 +08:00
|
|
|
Attaches a file with the given filename and content. The filename can
|
2009-06-12 21:56:40 +08:00
|
|
|
be omitted and the mimetype is guessed, if not provided.
|
2007-06-27 17:44:55 +08:00
|
|
|
|
2007-06-27 20:18:05 +08:00
|
|
|
If the first parameter is a MIMEBase subclass it is inserted directly
|
|
|
|
into the resulting message attachments.
|
2007-06-27 17:44:55 +08:00
|
|
|
"""
|
|
|
|
if isinstance(filename, MIMEBase):
|
2007-06-27 20:18:05 +08:00
|
|
|
assert content == mimetype == None
|
2007-07-06 14:53:27 +08:00
|
|
|
self.attachments.append(filename)
|
2007-06-27 17:44:55 +08:00
|
|
|
else:
|
|
|
|
assert content is not None
|
|
|
|
self.attachments.append((filename, content, mimetype))
|
|
|
|
|
|
|
|
def attach_file(self, path, mimetype=None):
|
|
|
|
"""Attaches a file from the filesystem."""
|
|
|
|
filename = os.path.basename(path)
|
|
|
|
content = open(path, 'rb').read()
|
|
|
|
self.attach(filename, content, mimetype)
|
|
|
|
|
2009-06-12 21:56:40 +08:00
|
|
|
def _create_message(self, msg):
|
|
|
|
return self._create_attachments(msg)
|
|
|
|
|
|
|
|
def _create_attachments(self, msg):
|
|
|
|
if self.attachments:
|
2010-03-06 05:27:58 +08:00
|
|
|
encoding = self.encoding or settings.DEFAULT_CHARSET
|
2009-06-12 21:56:40 +08:00
|
|
|
body_msg = msg
|
2010-03-06 05:27:58 +08:00
|
|
|
msg = SafeMIMEMultipart(_subtype=self.mixed_subtype, encoding=encoding)
|
2009-06-12 21:56:40 +08:00
|
|
|
if self.body:
|
|
|
|
msg.attach(body_msg)
|
|
|
|
for attachment in self.attachments:
|
|
|
|
if isinstance(attachment, MIMEBase):
|
|
|
|
msg.attach(attachment)
|
|
|
|
else:
|
|
|
|
msg.attach(self._create_attachment(*attachment))
|
|
|
|
return msg
|
|
|
|
|
|
|
|
def _create_mime_attachment(self, content, mimetype):
|
2007-06-27 17:44:55 +08:00
|
|
|
"""
|
2009-06-12 21:56:40 +08:00
|
|
|
Converts the content, mimetype pair into a MIME attachment object.
|
2007-06-27 17:44:55 +08:00
|
|
|
"""
|
|
|
|
basetype, subtype = mimetype.split('/', 1)
|
|
|
|
if basetype == 'text':
|
2010-03-06 05:27:58 +08:00
|
|
|
encoding = self.encoding or settings.DEFAULT_CHARSET
|
|
|
|
attachment = SafeMIMEText(smart_str(content, encoding), subtype, encoding)
|
2007-06-27 17:44:55 +08:00
|
|
|
else:
|
|
|
|
# Encode non-text attachments with base64.
|
|
|
|
attachment = MIMEBase(basetype, subtype)
|
|
|
|
attachment.set_payload(content)
|
|
|
|
Encoders.encode_base64(attachment)
|
2009-06-12 21:56:40 +08:00
|
|
|
return attachment
|
|
|
|
|
|
|
|
def _create_attachment(self, filename, content, mimetype=None):
|
|
|
|
"""
|
|
|
|
Converts the filename, content, mimetype triple into a MIME attachment
|
|
|
|
object.
|
|
|
|
"""
|
|
|
|
if mimetype is None:
|
|
|
|
mimetype, _ = mimetypes.guess_type(filename)
|
|
|
|
if mimetype is None:
|
|
|
|
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
|
|
|
|
attachment = self._create_mime_attachment(content, mimetype)
|
2007-06-27 20:18:05 +08:00
|
|
|
if filename:
|
2008-03-22 05:52:34 +08:00
|
|
|
attachment.add_header('Content-Disposition', 'attachment',
|
|
|
|
filename=filename)
|
2007-06-27 17:44:55 +08:00
|
|
|
return attachment
|
|
|
|
|
2009-11-03 20:53:26 +08:00
|
|
|
|
2007-06-27 20:18:05 +08:00
|
|
|
class EmailMultiAlternatives(EmailMessage):
|
|
|
|
"""
|
|
|
|
A version of EmailMessage that makes it easy to send multipart/alternative
|
|
|
|
messages. For example, including text and HTML versions of the text is
|
|
|
|
made easier.
|
|
|
|
"""
|
2009-06-12 21:56:40 +08:00
|
|
|
alternative_subtype = 'alternative'
|
2007-06-27 20:18:05 +08:00
|
|
|
|
2009-06-12 21:56:40 +08:00
|
|
|
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
|
|
|
|
connection=None, attachments=None, headers=None, alternatives=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.
|
|
|
|
"""
|
|
|
|
super(EmailMultiAlternatives, self).__init__(subject, body, from_email, to, bcc, connection, attachments, headers)
|
|
|
|
self.alternatives=alternatives or []
|
|
|
|
|
|
|
|
def attach_alternative(self, content, mimetype):
|
2007-06-27 20:18:05 +08:00
|
|
|
"""Attach an alternative content representation."""
|
2009-06-12 21:56:40 +08:00
|
|
|
assert content is not None
|
|
|
|
assert mimetype is not None
|
|
|
|
self.alternatives.append((content, mimetype))
|
|
|
|
|
|
|
|
def _create_message(self, msg):
|
|
|
|
return self._create_attachments(self._create_alternatives(msg))
|
|
|
|
|
|
|
|
def _create_alternatives(self, msg):
|
2010-03-06 05:27:58 +08:00
|
|
|
encoding = self.encoding or settings.DEFAULT_CHARSET
|
2009-06-12 21:56:40 +08:00
|
|
|
if self.alternatives:
|
|
|
|
body_msg = msg
|
2010-03-06 05:27:58 +08:00
|
|
|
msg = SafeMIMEMultipart(_subtype=self.alternative_subtype, encoding=encoding)
|
2009-06-12 21:56:40 +08:00
|
|
|
if self.body:
|
|
|
|
msg.attach(body_msg)
|
|
|
|
for alternative in self.alternatives:
|
|
|
|
msg.attach(self._create_mime_attachment(*alternative))
|
|
|
|
return msg
|