Ticket #9367: mail.py

File mail.py, 2.8 KB (added by loekje, 16 years ago)

Example of EmailAlternativesMessage with support of including, next to alternative views, attachments

Line 
1from email import Encoders
2from email.MIMEBase import MIMEBase
3from email.Utils import formatdate
4
5from django.core.mail import make_msgid, SafeMIMEText, SafeMIMEMultipart
6from django.core.mail import EmailMessage
7from django.conf import settings
8from django.utils.encoding import smart_str
9
10class EmailAlternativesMessage(EmailMessage):
11 def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
12 connection=None, attachments=None, headers=None, alternatives=None):
13 super(EmailAlternativesMessage, self).__init__(subject, body,
14 from_email, to, bcc, connection, attachments, headers)
15 self.alternatives=alternatives or []
16
17 def message(self):
18 encoding = self.encoding or settings.DEFAULT_CHARSET
19 msg = SafeMIMEText(smart_str(self.body, settings.DEFAULT_CHARSET),
20 self.content_subtype, encoding)
21 if self.alternatives:
22 body_msg = msg
23 msg = SafeMIMEMultipart(_subtype='alternative')
24 if self.body:
25 msg.attach(body_msg)
26 for alternative in self.alternatives:
27 if isinstance(alternative, MIMEBase):
28 msg.attach(alternative)
29 else:
30 msg.attach(self._create_alternative(*alternative))
31 if self.attachments:
32 body_msg = msg
33 msg = SafeMIMEMultipart(_subtype=self.multipart_subtype)
34 if self.body:
35 msg.attach(body_msg)
36 for attachment in self.attachments:
37 if isinstance(attachment, MIMEBase):
38 msg.attach(attachment)
39 else:
40 msg.attach(self._create_attachment(*attachment))
41 msg['Subject'] = self.subject
42 msg['From'] = self.from_email
43 msg['To'] = ', '.join(self.to)
44 msg['Date'] = formatdate()
45 msg['Message-ID'] = make_msgid()
46 for name, value in self.extra_headers.items():
47 msg[name] = value
48 return msg
49
50 def attach_alternative(self, content=None, mimetype=None):
51 """Attach an alternative content representation."""
52 assert content is not None
53 assert mimetype is not None
54 self.alternatives.append((content, mimetype))
55
56 def _create_alternative(self, content, mimetype):
57 """
58 Converts the content, mimetype pair into a MIME attachment object.
59 """
60 basetype, subtype = mimetype.split('/', 1)
61 if basetype == 'text':
62 alternative = SafeMIMEText(smart_str(content,
63 settings.DEFAULT_CHARSET), subtype, settings.DEFAULT_CHARSET)
64 else:
65 alternative = MIMEBase(basetype, subtype)
66 alternative.set_payload(content)
67 Encoders.encode_base64(attachment)
68 return alternative
69
Back to Top