-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmailer.py
443 lines (354 loc) · 13.7 KB
/
mailer.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
432
433
434
435
436
437
438
439
440
441
442
443
#coding: UTF8
"""
mailer module
Simple front end to the smtplib and email modules,
to simplify sending email.
A lot of this code was taken from the online examples in the
email module documentation:
http://docs.python.org/library/email-examples.html
Released under MIT license.
Version 0.5 is based on a patch by Douglas Mayle
Sample code:
import mailer
message = mailer.Message()
message.From = "[email protected]"
message.To = "[email protected]"
message.Subject = "My Vacation"
message.Body = open("letter.txt", "rb").read()
message.attach("picture.jpg")
sender = mailer.Mailer('mail.example.com')
sender.send(message)
"""
import smtplib
import threading
import Queue
import uuid
# this is to support name changes
# from version 2.4 to version 2.5
try:
from email import encoders
from email.header import make_header
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
except ImportError:
from email import Encoders as encoders
from email.Header import make_header
from email.MIMEMessage import Message
from email.MIMEAudio import MIMEAudio
from email.MIMEBase import MIMEBase
from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
# For guessing MIME type based on file name extension
import mimetypes
import time
from os import path
__version__ = "0.7"
__author__ = "Ryan Ginstrom"
__license__ = "MIT"
__description__ = "A module to send email simply in Python"
class Mailer(object):
"""
Represents an SMTP connection.
Use login() to log in with a username and password.
"""
def __init__(self, host="localhost", port=0, use_tls=False, usr=None,
pwd=None, use_ssl=False):
self.host = host
self.port = port
self.use_tls = use_tls
self.use_ssl = use_ssl
self._usr = usr
self._pwd = pwd
def login(self, usr, pwd):
self._usr = usr
self._pwd = pwd
def send(self, msg, recips=None):
"""
Send one message or a sequence of messages.
Every time you call send, the mailer creates a new
connection, so if you have several emails to send, pass
them as a list:
mailer.send([msg1, msg2, msg3])
Keyword arguments:
recips --- If None, the message will be sent to the to + cc + bcc
recipients in the message header. Else, if this is a list of
addresses, it will be sent to only the addrs listed.
"""
if recips == [None,]:
# I don't know why this param gets this input sometimes, but it is
# causing mail sending to fail.
recips = None
if self.use_ssl:
server = smtplib.SMTP_SSL(self.host, self.port)
else:
server = smtplib.SMTP(self.host, self.port)
if self._usr and self._pwd:
if self.use_tls is True:
server.ehlo()
server.starttls()
server.ehlo()
server.login(self._usr, self._pwd)
try:
num_msgs = len(msg)
for m in msg:
self._send(server, m, recips=recips)
except TypeError:
self._send(server, msg, recips=recips)
server.quit()
def _send(self, server, msg, recips=None):
"""
Sends a single message using the server
we created in send()
Keyword arguments:
recips --- If None, the message will be sent to the to + cc + bcc
recipients in the message header. Else, if this is a list of
addresses, it will be sent to only the addrs listed.
"""
me = msg.From
if isinstance(msg.To, basestring):
to = [msg.To]
else:
to = list(msg.To)
cc = []
if msg.CC:
if isinstance(msg.CC, basestring):
cc = [msg.CC]
else:
cc = list(msg.CC)
bcc = []
if msg.BCC:
if isinstance(msg.BCC, basestring):
bcc = [msg.BCC]
else:
bcc = list(msg.BCC)
if recips is None:
you = to + cc + bcc
else:
if isinstance(recips, basestring):
you = [recips]
else:
you = recips
server.sendmail(me, you, msg.as_string())
class Message(object):
"""
Represents an email message.
Set the To, From, Subject, and Body attributes as plain-text strings.
Optionally, set the Html attribute to send an HTML email, or use the
attach() method to attach files.
Use the charset property to send messages using other than us-ascii
If you specify an attachments argument, it should be a list of
attachment filenames: ["file1.txt", "file2.txt"]
If you specify an additional_headers argument, it should be a
dictionary of header:value associations: {"X-Magic": "Black"}
`To` should be a string for a single address, and a sequence
of strings for multiple recipients (castable to list)
Send using the Mailer class.
"""
def __init__(self, To=None, From=None, CC=None, BCC=None, Subject=None, Body=None, Html=None,
Date=None, attachments=None, additional_headers=None, charset=None):
self.attachments = []
if attachments:
for attachment in attachments:
if isinstance(attachment, basestring):
self.attachments.append((attachment, None, None))
else:
try:
filename, cid = attachment
except (TypeError, IndexError):
self.attachments.append((attachment, None, None))
else:
self.attachments.append((filename, cid, None))
self.To = To
self.CC = CC
self.BCC = BCC
"""string or iterable"""
self.From = From
"""string"""
self.Subject = Subject
self.Body = Body
self.Html = Html
self.Date = Date or time.strftime("%a, %d %b %Y %H:%M:%S %z", time.gmtime())
self.additional_headers = additional_headers
self.charset = charset or 'us-ascii'
self.message_id = self.make_key()
def make_key(self):
return str(uuid.uuid4())
def as_string(self):
"""Get the email as a string to send in the mailer"""
if not self.attachments:
return self._plaintext()
else:
return self._multipart()
def _plaintext(self):
"""Plain text email with no attachments"""
if not self.Html:
msg = MIMEText(self.Body, 'plain', self.charset)
else:
msg = self._with_html()
self._set_info(msg)
return msg.as_string()
def _with_html(self):
"""There's an html part"""
outer = MIMEMultipart('alternative')
part1 = MIMEText(self.Body, 'plain', self.charset)
part2 = MIMEText(self.Html, 'html', self.charset)
outer.attach(part1)
outer.attach(part2)
return outer
def _set_info(self, msg):
if hasattr(self.additional_headers, 'items'):
for ahkey, value in self.additional_headers.items():
msg.add_header(ahkey, value);
if self.charset == 'us-ascii':
msg['Subject'] = self.Subject
else:
subject = unicode(self.Subject, self.charset)
msg['Subject'] = str(make_header([(subject, self.charset)]))
msg['From'] = self.From
if isinstance(self.To, basestring):
msg['To'] = self.To
else:
self.To = list(self.To)
msg['To'] = ", ".join(self.To)
if self.CC:
if isinstance(self.CC, basestring):
msg['CC'] = self.CC
else:
self.CC = list(self.CC)
msg['CC'] = ", ".join(self.CC)
msg['Date'] = self.Date
def _multipart(self):
"""The email has attachments"""
msg = MIMEMultipart('related')
if self.Html:
outer = MIMEMultipart('alternative')
part1 = MIMEText(self.Body, 'plain', self.charset)
part1.add_header('Content-Disposition', 'inline')
part2 = MIMEText(self.Html, 'html', self.charset)
part2.add_header('Content-Disposition', 'inline')
outer.attach(part1)
outer.attach(part2)
msg.attach(outer)
else:
msg.attach(MIMEText(self.Body, 'plain', self.charset))
self._set_info(msg)
msg.preamble = self.Subject
for filename, cid, mimetype in self.attachments:
self._add_attachment(msg, filename, cid, mimetype)
return msg.as_string()
def _add_attachment(self, outer, attachment, cid, mimetype):
"""
If mimetype is None, it will try to guess the mimetype
"""
if isinstance(attachment, basestring):
filename = attachment
with open(filename) as fd:
atchcont = fd.read()
elif hasattr(attachment, 'name') and hasattr(attachment, 'read'):
filename = attachment.name
atchcont = attachment.read()
else:
raise ValueError(
"Attachment must be a file path or a named file-like object")
if mimetype:
ctype = mimetype
encoding = None
else:
ctype, encoding = mimetypes.guess_type(filename)
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
if maintype == 'text':
# TODO: we should handle calculating the charset
# (but in the meantime, utf-8 is a better default than us-ascii!)
msg = MIMEText(atchcont, _subtype=subtype, _charset='utf-8')
elif maintype == 'image':
msg = MIMEImage(atchcont, _subtype=subtype)
elif maintype == 'audio':
msg = MIMEAudio(atchcont, _subtype=subtype)
else:
msg = MIMEBase(maintype, subtype)
msg.set_payload(atchcont)
# Encode the payload using Base64
encoders.encode_base64(msg)
# Set the content-ID header
if cid:
msg.add_header('Content-ID', '<%s>' % cid)
msg.add_header('Content-Disposition', 'inline')
else:
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=path.basename(filename))
outer.attach(msg)
def attach(self, filename, cid=None, mimetype=None):
"""
Attach a file to the email. Specify the name of the file;
Message will figure out the MIME type and load the file.
Specify mimetype to set the MIME type manually.
"""
self.attachments.append((filename, cid, mimetype))
class Manager(threading.Thread):
"""
Manages the sending of email in the background
you can supply it with an instance of class Mailler or pass in the same
parameters that you would have used to create an instance of Mailler
if a message was succesfully sent, self.results[msg.message_id] returns a 3
element tuple (True/False, err_code, err_message)
"""
def __init__(self, mailer=None, callback=None, **kwargs):
threading.Thread.__init__(self)
self.queue = Queue.Queue()
self.mailer = mailer
self.abort = False
self.callback = callback
self._results = {}
self._result_lock = threading.RLock()
if self.mailer is None:
self.mailer = Mailer(
host=kwargs.get('host', 'localhost'),
port=kwargs.get('port', 25),
use_tls=kwargs.get('use_tls', False),
usr=kwargs.get('usr', None),
pwd=kwargs.get('pwd', None),
)
def __getattr__(self, name):
if name == 'results':
with self._result_lock:
return self._results
else:
return None
def run(self):
while self.abort is False:
msg = self.queue.get(block=True)
if msg is None:
break
try:
num_msgs = len(msg)
except TypeError:
num_msgs = 1
msg = [msg]
for m in msg:
try:
self.results[m.message_id] = (False, -1, '')
self.mailer.send(m)
self.results[m.message_id] = (True, 0, '')
except Exception as e:
args = e.args
if len(args) < 2:
args = (-1, e.args[0])
self.results[m.message_id] = (False, args[0], args[1])
if self.callback:
try:
self.callback(m.message_id)
except:
pass
# endfor
self.queue.task_done()
def send(self, msg):
self.queue.put(msg)