-
Notifications
You must be signed in to change notification settings - Fork 27
/
sender.py
431 lines (351 loc) · 13.7 KB
/
sender.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# -*- coding: utf-8 -*-
"""
sender
~~~~~~
Python SMTP Client for Humans.
:copyright: (c) 2016 by Shipeng Feng.
:license: BSD, see LICENSE for more details.
"""
__version__ = '0.3'
import sys
import smtplib
import time
from email import charset
from email.encoders import encode_base64
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import make_msgid, formataddr, parseaddr, formatdate
from email.header import Header
charset.add_charset('utf-8', charset.SHORTEST, None, 'utf-8')
PY2 = sys.version_info[0] == 2
if not PY2:
text_type = str
string_types = (str,)
integer_types = (int,)
iterkeys = lambda d: iter(d.keys())
itervalues = lambda d: iter(d.values())
iteritems = lambda d: iter(d.items())
else:
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
iterkeys = lambda d: d.iterkeys()
itervalues = lambda d: d.itervalues()
iteritems = lambda d: d.iteritems()
class Mail(object):
"""Sender Mail main class. This class is used for manage SMTP server
connections and send messages.
:param host: smtp server host, default to be 'localhost'
:param username: smtp server authentication username
:param password: smtp server authentication password
:param port: smtp server port, default to be 25
:param use_tls: put the SMTP connection in TLS (Transport Layer Security)
mode, default to be False
:param use_ssl: put the SMTP connection in SSL mode, default to be False
:param debug_level: the debug output level
:param fromaddr: default sender for all messages sent by this mail instance
"""
def __init__(self, host='localhost', username=None, password=None,
port=25, use_tls=False, use_ssl=False, debug_level=None,
fromaddr=None):
self.host = host
self.port = port
self.username = username
self.password = password
self.use_tls = use_tls
self.use_ssl = use_ssl
self.debug_level = debug_level
self.fromaddr = fromaddr
@property
def connection(self):
"""Open one connection to the SMTP server.
"""
return Connection(self)
def send(self, message_or_messages):
"""Sends a single messsage or multiple messages.
:param message_or_messages: one message instance or one iterable of
message instances.
"""
try:
messages = iter(message_or_messages)
except TypeError:
messages = [message_or_messages]
with self.connection as c:
for message in messages:
if self.fromaddr and not message.fromaddr:
message.fromaddr = self.fromaddr
message.validate()
c.send(message)
def send_message(self, *args, **kwargs):
"""Shortcut for send.
"""
self.send(Message(*args, **kwargs))
class Connection(object):
"""This class handles connection to the SMTP server. Instance of this
class would be one context manager so that you do not have to manage
connection close manually.
TODO: connection pool?
:param mail: one mail instance
"""
def __init__(self, mail):
self.mail = mail
def __enter__(self):
if self.mail.use_ssl:
server = smtplib.SMTP_SSL(self.mail.host, self.mail.port)
else:
server = smtplib.SMTP(self.mail.host, self.mail.port)
# Set the debug output level
if self.mail.debug_level is not None:
server.set_debuglevel(int(self.mail.debug_level))
if self.mail.use_tls:
server.starttls()
if self.mail.username and self.mail.password:
server.login(self.mail.username, self.mail.password)
self.server = server
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self.server.quit()
def send(self, message):
"""Send one message instance.
:param message: one message instance.
"""
self.server.sendmail(message.fromaddr, message.to_addrs,
str(message) if PY2 else message.as_bytes(),
message.mail_options, message.rcpt_options)
class AddressAttribute(object):
"""Makes an address attribute forward to the addrs"""
def __init__(self, name):
self.__name__ = name
def __get__(self, obj, type=None):
if obj is None:
return self
return obj.addrs[self.__name__]
def __set__(self, obj, value):
if value is None:
obj.addrs[self.__name__] = value
return
if self.__name__ in ('to', 'cc', 'bcc'):
if isinstance(value, string_types):
value = [value]
if self.__name__ == 'fromaddr':
value = process_address(parse_fromaddr(value), obj.charset)
elif self.__name__ in ('to', 'cc', 'bcc'):
value = set(process_addresses(value, obj.charset))
elif self.__name__ == 'reply_to':
value = process_address(value, obj.charset)
obj.addrs[self.__name__] = value
class Message(object):
"""One email message.
:param subject: message subject
:param to: message recipient, should be one or a list of addresses
:param body: plain text content body
:param html: HTML content body
:param fromaddr: message sender, can be one address or a two-element tuple
:param cc: CC list, should be one or a list of addresses
:param bcc: BCC list, should be one or a list of addresses
:param attachments: a list of attachment instances
:param reply_to: reply-to address
:param date: message send date, seconds since the Epoch,
default to be time.time()
:param charset: message charset, default to be 'utf-8'
:param extra_headers: a dictionary of extra headers
:param mail_options: a list of ESMTP options used in MAIL FROM commands
:param rcpt_options: a list of ESMTP options used in RCPT commands
"""
to = AddressAttribute('to')
fromaddr = AddressAttribute('fromaddr')
cc = AddressAttribute('cc')
bcc = AddressAttribute('bcc')
reply_to = AddressAttribute('reply_to')
def __init__(self, subject=None, to=None, body=None, html=None,
fromaddr=None, cc=None, bcc=None, attachments=None,
reply_to=None, date=None, charset='utf-8',
extra_headers=None, mail_options=None, rcpt_options=None):
self.message_id = make_msgid()
self.subject = subject
self.body = body
self.html = html
self.attachments = attachments or []
self.date = date
self.charset = charset
self.extra_headers = extra_headers
self.mail_options = mail_options or []
self.rcpt_options = rcpt_options or []
# used for actual addresses store
self.addrs = dict()
# set address
self.to = to or []
self.fromaddr = fromaddr
self.cc = cc or []
self.bcc = bcc or []
self.reply_to = reply_to
@property
def to_addrs(self):
return self.to | self.cc | self.bcc
def validate(self):
"""Do email message validation.
"""
if not (self.to or self.cc or self.bcc):
raise SenderError("does not specify any recipients(to,cc,bcc)")
if not self.fromaddr:
raise SenderError("does not specify fromaddr(sender)")
for c in '\r\n':
if self.subject and (c in self.subject):
raise SenderError('newline is not allowed in subject')
def as_string(self):
"""The message string.
"""
if self.date is None:
self.date = time.time()
if not self.html:
if len(self.attachments) == 0:
# plain text
msg = MIMEText(self.body, 'plain', self.charset)
elif len(self.attachments) > 0:
# plain text with attachments
msg = MIMEMultipart()
msg.attach(MIMEText(self.body, 'plain', self.charset))
else:
msg = MIMEMultipart()
alternative = MIMEMultipart('alternative')
alternative.attach(MIMEText(self.body, 'plain', self.charset))
alternative.attach(MIMEText(self.html, 'html', self.charset))
msg.attach(alternative)
msg['Subject'] = Header(self.subject, self.charset)
msg['From'] = self.fromaddr
msg['To'] = ', '.join(self.to)
msg['Date'] = formatdate(self.date, localtime=True)
msg['Message-ID'] = self.message_id
if self.cc:
msg['Cc'] = ', '.join(self.cc)
if self.reply_to:
msg['Reply-To'] = self.reply_to
if self.extra_headers:
for key, value in self.extra_headers.items():
msg[key] = value
for attachment in self.attachments:
f = MIMEBase(*attachment.content_type.split('/'))
f.set_payload(attachment.data)
encode_base64(f)
if attachment.filename is None:
filename = str(None)
else:
filename = force_text(attachment.filename, self.charset)
try:
filename.encode('ascii')
except UnicodeEncodeError:
if PY2:
filename = filename.encode('utf-8')
filename = ('UTF8', '', filename)
f.add_header('Content-Disposition', attachment.disposition,
filename=filename)
for key, value in attachment.headers.items():
f.add_header(key, value)
msg.attach(f)
return msg.as_string()
def as_bytes(self):
return self.as_string().encode(self.charset or 'utf-8')
def __str__(self):
return self.as_string()
def attach(self, attachment_or_attachments):
"""Adds one or a list of attachments to the message.
:param attachment_or_attachments: one or an iterable of attachments
"""
try:
attachments = iter(attachment_or_attachments)
except TypeError:
attachments = [attachment_or_attachments]
self.attachments.extend(attachments)
def attach_attachment(self, *args, **kwargs):
"""Shortcut for attach.
"""
self.attach(Attachment(*args, **kwargs))
class Attachment(object):
"""File attachment information.
:param filename: filename
:param content_type: file mimetype
:param data: raw data
:param disposition: content-disposition, default to be 'attachment'
:param headers: a dictionary of headers, default to be {}
"""
def __init__(self, filename=None, content_type=None, data=None,
disposition='attachment', headers={}):
self.filename = filename
self.content_type = content_type
self.data = data
self.disposition = disposition
self.headers = headers
def parse_fromaddr(fromaddr):
"""Generate an RFC 822 from-address string.
Simple usage::
>>> parse_fromaddr('[email protected]')
>>> parse_fromaddr(('from', '[email protected]'))
'from <[email protected]>'
:param fromaddr: string or tuple
"""
if isinstance(fromaddr, tuple):
fromaddr = "%s <%s>" % fromaddr
return fromaddr
class SenderUnicodeDecodeError(UnicodeDecodeError):
def __init__(self, obj, *args):
self.obj = obj
UnicodeDecodeError.__init__(self, *args)
def __str__(self):
original = UnicodeDecodeError.__str__(self)
return '%s. You passed in %r (%s)' % (original, self.obj,
type(self.obj))
class SenderError(Exception):
pass
def force_text(s, encoding='utf-8', errors='strict'):
"""Returns a unicode object representing 's'. Treats bytestrings using
the 'encoding' codec.
:param s: one string
:param encoding: the input encoding
:param errors: values that are accepted by Python’s unicode() function
for its error handling
"""
if isinstance(s, text_type):
return s
try:
if not isinstance(s, string_types):
if not PY2:
if isinstance(s, bytes):
s = text_type(s, encoding, errors)
else:
s = text_type(s)
elif hasattr(s, '__unicode__'):
s = s.__unicode__()
else:
s = text_type(bytes(s), encoding, errors)
else:
s = s.decode(encoding, errors)
except UnicodeDecodeError as e:
if not isinstance(s, Exception):
raise SenderUnicodeDecodeError(s, *e.args)
else:
s = ' '.join([force_text(arg, encoding, errors) for arg in s])
return s
def process_address(address, encoding='utf-8'):
"""Process one email address.
:param address: email from-address string
"""
name, addr = parseaddr(force_text(address, encoding))
try:
name = Header(name, encoding).encode()
except UnicodeEncodeError:
name = Header(name, 'utf-8').encode()
try:
addr.encode('ascii')
except UnicodeEncodeError:
if '@' in addr:
localpart, domain = addr.split('@', 1)
localpart = str(Header(localpart, encoding))
domain = domain.encode('idna').decode('ascii')
addr = '@'.join([localpart, domain])
else:
addr = Header(addr, encoding).encode()
return formataddr((name, addr))
def process_addresses(addresses, encoding='utf-8'):
return map(lambda e: process_address(e, encoding), addresses)