-
Notifications
You must be signed in to change notification settings - Fork 57
/
envelope.py
330 lines (263 loc) · 10.2 KB
/
envelope.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Tomasz Wójcik <tomek@bthlabs.pl>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
"""
envelopes.envelope
==================
This module contains the Envelope class.
"""
import sys
if sys.version_info[0] == 2:
from email import Encoders as email_encoders
elif sys.version_info[0] == 3:
from email import encoders as email_encoders
basestring = str
def unicode(_str, _charset):
return str(_str.encode(_charset), _charset)
else:
raise RuntimeError('Unsupported Python version: %d.%d.%d' % (
sys.version_info[0], sys.version_info[1], sys.version_info[2]
))
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
import mimetypes
import os
import re
from .conn import SMTP
from .compat import encoded
class MessageEncodeError(Exception):
pass
class Envelope(object):
"""
The Envelope class.
**Address formats**
The following formats are supported for e-mail addresses:
* ``"user@server.com"`` - just the e-mail address part as a string,
* ``"Some User <user@server.com>"`` - name and e-mail address parts as a string,
* ``("user@server.com", "Some User")`` - e-mail address and name parts as a tuple.
Whenever you come to manipulate addresses feel free to use any (or all) of
the formats above.
:param to_addr: ``To`` address or list of ``To`` addresses
:param from_addr: ``From`` address
:param subject: message subject
:param html_body: optional HTML part of the message
:param text_body: optional plain text part of the message
:param cc_addr: optional single CC address or list of CC addresses
:param bcc_addr: optional single BCC address or list of BCC addresses
:param headers: optional dictionary of headers
:param charset: message charset
"""
ADDR_FORMAT = '%s <%s>'
ADDR_REGEXP = re.compile(r'^(.*) <([^@]+@[^@]+)>$')
def __init__(self, to_addr=None, from_addr=None, subject=None,
html_body=None, text_body=None, cc_addr=None, bcc_addr=None,
headers=None, charset='utf-8'):
if to_addr:
if isinstance(to_addr, list):
self._to = to_addr
else:
self._to = [to_addr]
else:
self._to = []
self._from = from_addr
self._subject = subject
self._parts = []
if text_body:
self._parts.append(('text/plain', text_body, charset))
if html_body:
self._parts.append(('text/html', html_body, charset))
if cc_addr:
if isinstance(cc_addr, list):
self._cc = cc_addr
else:
self._cc = [cc_addr]
else:
self._cc = []
if bcc_addr:
if isinstance(bcc_addr, list):
self._bcc = bcc_addr
else:
self._bcc = [bcc_addr]
else:
self._bcc = []
if headers:
self._headers = headers
else:
self._headers = {}
self._charset = charset
self._addr_format = unicode(self.ADDR_FORMAT, charset)
def __repr__(self):
return u'<Envelope from="%s" to="%s" subject="%s">' % (
self._addrs_to_header([self._from]),
self._addrs_to_header(self._to),
self._subject
)
@property
def to_addr(self):
"""List of ``To`` addresses."""
return self._to
def add_to_addr(self, to_addr):
"""Adds a ``To`` address."""
self._to.append(to_addr)
def clear_to_addr(self):
"""Clears list of ``To`` addresses."""
self._to = []
@property
def from_addr(self):
return self._from
@from_addr.setter
def from_addr(self, from_addr):
self._from = from_addr
@property
def cc_addr(self):
"""List of CC addresses."""
return self._cc
def add_cc_addr(self, cc_addr):
"""Adds a CC address."""
self._cc.append(cc_addr)
def clear_cc_addr(self):
"""Clears list of CC addresses."""
self._cc = []
@property
def bcc_addr(self):
"""List of BCC addresses."""
return self._bcc
def add_bcc_addr(self, bcc_addr):
"""Adds a BCC address."""
self._bcc.append(bcc_addr)
def clear_bcc_addr(self):
"""Clears list of BCC addresses."""
self._bcc = []
@property
def charset(self):
"""Message charset."""
return self._charset
@charset.setter
def charset(self, charset):
self._charset = charset
self._addr_format = unicode(self.ADDR_FORMAT, charset)
def _addr_tuple_to_addr(self, addr_tuple):
addr = ''
if len(addr_tuple) == 2 and addr_tuple[1]:
addr = self._addr_format % (
self._header(addr_tuple[1] or ''),
addr_tuple[0] or ''
)
elif addr_tuple[0]:
addr = addr_tuple[0]
return addr
@property
def headers(self):
"""Dictionary of custom headers."""
return self._headers
def add_header(self, key, value):
"""Adds a custom header."""
self._headers[key] = value
def clear_headers(self):
"""Clears custom headers."""
self._headers = {}
def _addrs_to_header(self, addrs):
_addrs = []
for addr in addrs:
if not addr:
continue
if isinstance(addr, basestring):
if self._is_ascii(addr):
_addrs.append(self._encoded(addr))
else:
# these headers need special care when encoding, see:
# http://tools.ietf.org/html/rfc2047#section-8
# Need to break apart the name from the address if there are
# non-ascii chars
m = self.ADDR_REGEXP.match(addr)
if m:
t = (m.group(2), m.group(1))
_addrs.append(self._addr_tuple_to_addr(t))
else:
# What can we do? Just pass along what the user gave us and hope they did it right
_addrs.append(self._encoded(addr))
elif isinstance(addr, tuple):
_addrs.append(self._addr_tuple_to_addr(addr))
else:
self._raise(MessageEncodeError,
'%s is not a valid address' % str(addr))
_header = ','.join(_addrs)
return _header
def _raise(self, exc_class, message):
raise exc_class(self._encoded(message))
def _header(self, _str):
if self._is_ascii(_str):
return _str
return Header(_str, self._charset).encode()
def _is_ascii(self, _str):
return all(ord(c) < 128 for c in _str)
def _encoded(self, _str):
return encoded(_str, self._charset)
def to_mime_message(self):
"""Returns the envelope as
:py:class:`email.mime.multipart.MIMEMultipart`."""
msg = MIMEMultipart('alternative')
msg['Subject'] = self._header(self._subject or '')
msg['From'] = self._encoded(self._addrs_to_header([self._from]))
msg['To'] = self._encoded(self._addrs_to_header(self._to))
if self._cc:
msg['CC'] = self._addrs_to_header(self._cc)
if self._headers:
for key, value in self._headers.items():
msg[key] = self._header(value)
for part in self._parts:
type_maj, type_min = part[0].split('/')
if type_maj == 'text' and type_min in ('html', 'plain'):
msg.attach(MIMEText(part[1], type_min, self._charset))
else:
msg.attach(part[1])
return msg
def add_attachment(self, file_path, mimetype=None):
"""Attaches a file located at *file_path* to the envelope. If
*mimetype* is not specified an attempt to guess it is made. If nothing
is guessed then `application/octet-stream` is used."""
if not mimetype:
mimetype, _ = mimetypes.guess_type(file_path)
if mimetype is None:
mimetype = 'application/octet-stream'
type_maj, type_min = mimetype.split('/')
with open(file_path, 'rb') as fh:
part_data = fh.read()
part = MIMEBase(type_maj, type_min)
part.set_payload(part_data)
email_encoders.encode_base64(part)
part_filename = os.path.basename(self._encoded(file_path))
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% part_filename)
self._parts.append((mimetype, part))
def send(self, *args, **kwargs):
"""Sends the envelope using a freshly created SMTP connection. *args*
and *kwargs* are passed directly to :py:class:`envelopes.conn.SMTP`
constructor.
Returns a tuple of SMTP object and whatever its send method returns."""
conn = SMTP(*args, **kwargs)
send_result = conn.send(self)
return conn, send_result