-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmailtime.py
1529 lines (1123 loc) · 37.8 KB
/
mailtime.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import poplib, imaplib, smtplib
import email, email.parser, email.message, email.header, rfc822
import sys, os, os.path, re, datetime, time
import imp, pickle, argparse
import pprint, traceback
ABORT = "*abort*"
SEEN = "*seen*"
DELETE = "*delete*"
FORWARD = "*forward*"
TRANSFER = "*transfer*"
MOVE = "*move*"
COPY = "*copy*"
FLAG = "*flag*"
TAG = "*tag*"
class Action (object):
def __init__(self, atype):
self.atype = atype
def __str__(self):
return self.atype
class Dump (Action):
def __init__(self):
Action.__init__(self, "*dump*")
def perform(self, msg, service):
print msg_unicode( msg ).encode( "utf-8" ) #XXX: make charset configurable
print ""
class DumpHeaders (Action):
def __init__(self, *headers ):
Action.__init__(self, "*dump-headers*")
self.headers = headers
def perform(self, msg, service):
for h in self.headers:
vv = msg.get_all(h)
if vv:
for v in vv:
print "%s: %s" % (h, v)
print ""
class Forward (Action):
def __init__(self, dest, service = None):
Action.__init__(self, FORWARD)
self.dest = dest
self.service = service
def __str__(self):
return self.atype + " to " + self.dest
class Move (Action):
def __init__(self, folder):
Action.__init__(self, MOVE)
self.folder = folder
def __str__(self):
return self.atype + " to " + self.folder
class Copy (Action):
def __init__(self, folder):
Action.__init__(self, COPY)
self.folder = folder
def __str__(self):
return self.atype + " to " + self.folder
class Transfer (Action):
def __init__(self, service, folder = "INBOX"):
Action.__init__(self, TRANSFER)
self.service = service
self.folder = folder
def __str__(self):
return self.atype + " to " + self.folder + " on " + self.service
class Tag (Action):
def __init__(self, tags):
Action.__init__(self, TAG)
self.tags = tags
def __str__(self):
return self.atype + " with " + self.tags
abort_action = Action(ABORT)
seen_action = Action(SEEN)
delete_action = Action(DELETE)
flag_action = Action(FLAG)
dump_action = Dump()
list_action = DumpHeaders("Message-Id", "Subject", "From", "To", "Envelope-to", "Date")
class Filter:
def matches( self, msg ):
raise Exception("not implemented")
def __str__( self ):
return type(self)
class Yes (Filter):
def matches( self, msg ):
return True
def __str__( self ):
return "Yes"
class And (Filter):
def __init__(self, *filters):
self.filters = filters
def matches( self, msg ):
for f in self.filters:
if not f.matches( msg ):
return False
return True
def __str__( self ):
return "( " + reduce( lambda s, t: "%s and %s" % (s, t), self.filters ) + " )"
class Not (Filter):
def __init__(self, filter):
self.filter = filter
def matches( self, msg ):
return not self.filter.matches(msg)
def __str__( self ):
return "Not %s" % self.filter
class Or (Filter):
def __init__(self, *filters):
self.filters = filters
def matches( self, msg ):
for f in self.filters:
if f.matches( msg ):
return True
return False
def __str__( self ):
return "( " + reduce( lambda s, t: "%s or %s" % (s, t), self.filters ) + " )"
class HeaderFilter (Filter):
def __init__(self, header):
self.header = header
def matches( self, msg ):
#TODO: allow access to xx_vars here!
if self.header.startswith("xx_"):
try:
hh = getattr( msg, self.header )
except:
hh = None
else:
hh = msg.get_all(self.header)
if not type(hh) in (tuple, list, set):
hh = ( hh, )
if hh:
for h in hh:
h = decode_header_str( h )
if self.matches_value( h ):
return True
return False
def matches_value( self, v ):
return Exception("not implemented")
class Matches (HeaderFilter):
def __init__(self, header, regex, flags = 0):
HeaderFilter.__init__(self, header)
if type(regex) == str or type(regex) == unicode:
self.regex = re.compile(regex, flags)
else:
self.regex = regex
def matches_value( self, v ):
if v.startswith('^'):
m = self.regex.match( v )
else:
m = self.regex.search( v )
if m: return True
else: return False
def __str__( self ):
return "%s ~~ %s" % (self.header, self.regex.pattern)
class Equals (HeaderFilter):
def __init__(self, header, value):
HeaderFilter.__init__(self, header)
self.value = value
def matches_value( self, v ):
return v == self.value
def __str__( self ):
return "%s == %s" % (self.header, self.value)
class HasTag (Equals):
def __init__(self, tag):
Equals.__init__(self, "xx_flags", tag)
class Contains (Matches):
def __init__(self, header, value, case_sensitive = False):
if case_sensitive:
f = rs.CASE_SENSITIVE
else:
f = 0
if type(value) != str:
p = "(" + "|".join( map( lambda s: re.escape(s), value ) ) + ")"
else:
p = re.escape(value)
Matches.__init__(self, header, '.*' + p + '.*', f)
class Greater (HeaderFilter):
def __init__(self, header, value):
HeaderFilter.__init__(self, header)
self.value = value
def matches_value( self, v ):
return v > self.value
def __str__( self ):
return "%s > %s" % (self.header, self.value)
class Less (HeaderFilter):
def __init__(self, header, value):
HeaderFilter.__init__(self, header)
self.value = value
def matches_value( self, v ):
return v < self.value
def __str__( self ):
return "%s < %s" % (self.header, self.value)
class Older (HeaderFilter):
def __init__(self, header, age):
HeaderFilter.__init__(self, header)
if type(age) == str or type(age) == unicode:
if age.endswith("y"):
age = int(age[:-1]) * 365 * 24 * 60 * 60
elif age.endswith("w"):
age = int(age[:-1]) * 7 * 24 * 60 * 60
elif age.endswith("d"):
age = int(age[:-1]) * 24 * 60 * 60
elif age.endswith("h"):
age = int(age[:-1]) * 60 * 60
elif age.endswith("m"):
age = int(age[:-1]) * 60
elif age.endswith("s"):
age = int(age);
else:
age = int(age) * 24 * 60 * 60;
self.age = age
def matches_value( self, v ):
t0 = time.time()
then = rfc822.parsedate_tz( v )
t1 = rfc822.mktime_tz(then)
return (t0 - t1) > self.age
def __str__( self ):
return "%s older than %s seconds" % (self.header, self.value)
# --------------------------------------------------------------------------------------------
def trace(msg):
if debug:
if type( msg ) == unicode:
msg = msg.encode( "utf-8" ) #XXX: make charset configurable
print msg
def log(msg):
if not quiet:
if type( msg ) == unicode:
msg = msg.encode( "utf-8" ) #XXX: make charset configurable
print msg
def complain(msg):
if type( msg ) == unicode:
msg = msg.encode( "utf-8" ) #XXX: make charset configurable
print msg
class MailService (object):
def __init__(self, **connection_spec):
self.connection_spec = connection_spec
self.connection = None
self.dry = False
def open(self):
self.connection = self.connect_to(**self.connection_spec)
def close(self):
raise Exception("unimplemented")
#---------------------------------------------
def unwrap(self, re):
return re
def connect_to(self, *spec):
raise Exception("unimplemented")
class MailboxService (MailService):
def list_mailboxes(self):
raise Exception("unimplemented")
def get_continuation(self, msg, prev_continue = None):
try:
d = msg.xx_date_received
except:
d = msg["Date"]
if prev_continue and 'since' in prev_continue:
t = as_datetime( prev_continue['since'] )
if t > d:
d = t
since = d.__str__()
return { 'since': since }
def list_messages(self, max_messages = None, mailbox = "INBOX", **options ):
raise Exception("unimplemented")
def peek_headers(self, id):
raise Exception("unimplemented")
def fetch_message(self, id, peek = False):
raise Exception("unimplemented")
def delete_message(self, id):
raise Exception("unimplemented")
def apply_actions( self, id, msg, actions ):
atypes = get_action_types( actions )
if len(atypes) == 0 or ( len(atypes) == 1 and iter(atypes).next() == ABORT ):
return #shorten out
if self.dry:
log( u"ACTIONS FOR %s" % msg_unicode(msg) )
log( u" ACTION TYPES: %s" % atypes )
if not self.dry:
if SEEN in atypes or FORWARD in atypes or TRANSFER in atypes:
peek = (not SEEN in atypes)
if peek:
trace( "LOADING MSG %s IN PEEK MODE" % (id,) )
else:
trace( "RECEIVING MSG %s AND MARKING AS SEEN" % (id,) )
msg = self.fetch_message( id, peek )
has_body = True
for a in actions:
if self.dry:
if a.atype == ABORT:
break
log(" %s" % a);
continue
if a.atype == SEEN:
pass # already handled
elif a.atype == DELETE:
pass # handled later
elif a.atype == ABORT:
break
elif a.atype == FORWARD:
fwd_msg = make_forward_message(msg, a.dest)
if a.service:
srv = services[a.service]
else:
srv = services["smtp"]
log( u"FORWARDING %s ==> %s" % (msg_unicode(msg), a.dest) )
srv.send_message( fwd_msg )
elif a.atype == TRANSFER:
log( u"TRANSFERING %s ==> %s/%s" % (msg_unicode(msg), a.service, a.folder) )
srv = services[ a.service ]
srv.add_message( msg, a.folder ) #NOTE: only works with imap service
elif a.atype == COPY:
log( u"COPYING %s ==> %s" % (msg_unicode(msg), a.folder) )
self.copy_message( id, a.folder ) #NOTE: only works with imap service
elif a.atype == MOVE:
log( u"MOVING %s ==> %s" % (msg_unicode(msg), a.folder) )
self.move_message( id, a.folder ) #NOTE: only works with imap service
elif a.atype == FLAG:
log( u"FLAGGING %s" % (msg_unicode(msg)) )
self.update_flags( id, '\Flagged' ) #XXX: this is imap-specific
elif a.atype == TAG:
if not type(a.tags) == str and not type(a.tags) == unicode:
f = " ".join(a.tags)
else:
f = a.tags
log( u"TAGGING %s WITH %s" % (msg_unicode(msg), f) )
self.update_flags( id, f )
else:
try:
a.perform( msg, self )
except AttributeError:
raise Exception("Unknown action type `%s`; custom actions must implement method perform(Message, MailService)" % a.atype)
if not self.dry:
if DELETE in atypes:
log( u"DELETING %s" % (msg_unicode(msg),) )
self.delete_message( id )
def process_messages(self, filters, since = None, max_messages = None, mailbox = "INBOX", persist = None):
if since:
# override continuation
continuation = { 'since': since }
trace( "PROCESSING MESSAGES SINCE %s" % since );
elif persist is not None:
continuation = persist.get("continuation")
if continuation:
trace( "PROCESSING MESSAGES FROM CONTINUATION MARKER: %s" % continuation );
else:
trace( "PROCESSING MESSAGES (NO CONTINUATION FOUND)" );
continuation = {}
else:
continuation = {}
trace( "PROCESSING ALL MESSAGES" );
messages = self.list_messages(max_messages = max_messages, mailbox = mailbox, **continuation)
if not messages or len(messages) == 0:
return
trace( "PROCESSING %i MESSAGES" % len(messages) );
for id, msg in messages.items():
actions = get_message_actions( msg, filters )
if actions:
try:
self.apply_actions( id, msg, actions )
except Exception, e:
complain( u"ERROR: Failed to apply actions to %s: %s " % (msg_unicode(msg), e ) )
if persist is not None:
continuation = self.get_continuation( msg, continuation )
if persist is not None and continuation:
trace("PERSISTING CONTINUATION MARKER: %s" % continuation)
persist["continuation"] = continuation
def add_message(self, msg, folder):
raise Exception("unimplemented, not a directory service")
def move_message(self, id, folder):
raise Exception("unimplemented, not a directory service")
def copy_message(self, id, folder):
raise Exception("unimplemented, not a directory service")
def update_flags(self, id, flags):
raise Exception("unimplemented, not a directory service")
class MailTransportService (MailService):
def send_messages(self, messages):
for msg in messages:
fromaddr = msg["From"]
toaddrs = msg.get_all("Envelope-to")
if not toaddrs or len(toaddrs) == 0:
toaddrs = msg.get_all("To")
cc = msg.get_all("Cc")
bcc = msg.get_all("Bcc")
if cc: toaddrs.extend( cc )
if bcc: toaddrs.extend( bcc ) #XXX: how to handle this correctly? Unset header?
self.send_message_to( fromaddr, toaddrs, msg )
def send_message(self, msg, toaddrs = None, fromaddr = None):
if not fromaddr:
fromaddr = msg["From"]
if not toaddrs:
toaddrs = msg.get_all("Envelope-to")
if not toaddrs or len(toaddrs) == 0:
toaddrs = msg.get_all("To")
cc = msg.get_all("Cc")
bcc = msg.get_all("Bcc")
if cc: toaddrs.extend( cc )
if bcc: toaddrs.extend( bcc ) #XXX: how to handle this correctly? Unset header?
self.send_message_to(fromaddr, toaddrs, msg)
def send_message_to(self, fromaddr, toaddrs, msg):
raise Exception("unimplemented")
class Pop3Service ( MailboxService ):
def __init__(self, **connection_spec):
MailService.__init__(self, **connection_spec)
def unwrap( self, response ):
if type(response) != str:
code = response[0]
content = response[1]
else:
code = response
content = response
if not code.startswith( "+OK" ):
raise Exception("POP3 error: %s" % content)
return content
def connect_to( self,
host, user, password,
protocol = "pop3", security = None, auth = None,
port = None, timeout = None,
keyfile = None, certfile = None ):
if not security:
if not port: port = 110
trace( "CONNECTING TO POP3 %s@%s:%i" % (user, host, port) )
conn = poplib.POP3( host, port, timeout )
elif security == 'ssl':
if not port: port = 995
trace( "CONNECTING TO POP3/SSL %s@%s:%i" % (user, host, port) )
conn = poplib.POP3_SSL( host, port, timeout )
else: raise Exception("unknown security mode: %s", security)
welcome = self.unwrap( conn.getwelcome() )
if not auth:
conn.user(user)
conn.pass_(password)
elif auth == "rpop":
conn.rpop(user)
elif auth == "apop":
conn.apop(user, password)
else:
raise Exception("unknown auth method: %s", security)
return conn
def close(self):
if self.connection:
self.connection.quit()
self.connection = None
def list_mailboxes(self):
return [ "INBOX" ]
def list_messages(self, max_messages = None, mailbox = "INBOX", **options ):
if 'since' in options: since = options['from_uid']
else: since = None
(num, size) = self.connection.stat()
# fetch the newest n = max_messages messages
to_no = num
if not max_messages:
from_no = 1
else:
from_no = num - max_messages +1;
if from_no < 1: from_no = 1;
trace( "FETCHING MSG NO %i to %i" % (from_no, to_no) )
if since:
since = as_datetime( since )
#XXX: if "since" is set, use binary search to find first message!
messages = {}
for no in range(from_no, to_no+1):
msg = self.peek_headers(no)
if since:
if msg["Date"]:
d = as_datetime( rfc822.parsedate_tz( msg["Date"] ) ) #XXX: would be nice to use the date the mail was *received*
if not d < since:
#print "%s == %s < %s " % (d, msg["Date"], since)
since = None
else:
continue
else:
continue
messages[no] = msg
return messages
def peek_headers(self, id):
re = self.unwrap( self.connection.top(id, 0) )
raw = "\r\n".join( re )
msg = rfc822parser.parsestr( raw, True )
return msg
def fetch_message(self, id, peek = False):
if peek:
re = self.unwrap( self.connection.top(id, 2**31-1) )
else:
re = self.unwrap( self.connection.retr(id) )
raw = "\r\n".join( re )
msg = rfc822parser.parsestr( raw, True )
return msg
def delete_message(self, id):
self.unwrap( self.connection.delete(id) )
imap_part_pattern = re.compile( r'\s*([\w]+)|\s*"(.*?)"|\s*\((.*?)\)|\s*\{(\d+)\}\r\n' )
alphanumeric_pattern = re.compile( r'\w+' )
whitespace_pattern = re.compile( r'\s+' )
def imap_split( s ):
i = 0
parts = []
while i<len(s):
m = imap_part_pattern.match(s, i)
if not m:
raise Exception("can't parse line as IMAP tokens: %s" % s)
if m.group(4) is not None:
n = int(m.group(4))
a = m.span()[1]
i = a + n
p = s[a:i]
elif m.group(3) is not None:
p = m.group(3)
i = m.span()[1]
elif m.group(2) is not None:
p = m.group(2)
i = m.span()[1]
elif m.group(1) is not None:
p = m.group(1)
i = m.span()[1]
parts.append(p)
return tuple(parts)
month = (
'-',
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
)
def as_imap_date( d, with_time = False ):
if d.tzinfo:
tzd = d.tzinfo.utcoffset( d )
else:
tzd = tz.utcoffset( d )
ofs = tzd.total_seconds()
hofs = abs( ofs / 3600 )
mofs = abs( ofs - ( hofs * 3600 ) ) / 60
if with_time:
return "%2i-%s-%04i %02i:%02i:%02i %s%02i%02i" % (d.day, month[d.month], d.year, d.hour, d.minute, d.second,
'+' if ofs > 0 else '-', hofs, mofs )
else:
return "%2i-%s-%04i" % ( d.day, month[d.month], d.year )
def as_imap_date_time( d ):
return as_imap_date( d, True )
class Imap4Service ( MailboxService ):
def __init__(self, **connection_spec):
MailService.__init__(self, **connection_spec)
self.mailbox = None
self.caps = None
#FIXME: use uid commands
def unwrap( self, response ):
if not response:
return response
if response[0] != "OK" :
#pprint.pprint(response)
raise Exception( "IMAP4 error: %s" % " ".join(response[1]) )
return response[1]
def open(self):
MailService.open(self)
if "charset" in self.connection_spec:
self.charset = self.connection_spec['charset']
else:
self.charset = "utf-8"
self.caps = self.unwrap( self.connection.capability() )
#pprint.pprint( self.caps )
self.folders = self.unwrap( self.connection.list() )
#pprint.pprint( self.folders )
def connect_to( self,
host, user, password,
protocol = "imap4", security = None,
timeout = None, auth = None, auth_handler = None,
port = None, mailbox = None,
keyfile = None, certfile = None,
charset = "utf-8" ):
if not mailbox:
mailbox = "INBOX"
if not security:
if not port: port = 143
trace( "CONNECTING TO IMAP4 %s@%s:%i" % (user, host, port) )
conn = imaplib.IMAP4( host, port )
elif security == 'ssl':
if not port: port = 993
trace( "CONNECTING TO IMAP4/SSL %s@%s:%i" % (user, host, port) )
conn = imaplib.IMAP4_SSL( host, port, keyfile, certfile )
else: raise Exception("unknown security mode: %s", security)
#mail.debug = 10
if auth and auth_handler:
self.unwrap( conn.authenticate(auth, auth_handler) )
elif not auth:
self.unwrap( conn.login(user, password) )
elif auth in ("cram", "cram_md5", "cram-md5", "md5"):
self.unwrap( conn.login_cram_md5(user, password) )
else:
raise Exception("unknown auth method: %s", security)
return conn
def close(self):
if self.connection:
# commit deletions if neccessary
if self.mailbox is not None and not self.dry:
self.unwrap( self.connection.expunge() )
self.mailbox = None
# disconnect imap4
self.connection.logout()
self.connection = None
def list_mailboxes(self):
mailboxes = self.unwrap( self.connection.list( ) )
return [ imap_split(x)[2] for x in mailboxes ]
def get_continuation(self, msg, prev_continue = None):
try:
uid = msg.xx_uid
if prev_continue and 'from_uid' in prev_continue:
u = prev_continue['from_uid']
if u > uid:
uid = u
return { 'from_uid': int(uid) }
except:
pass
return super(Imap4Service, self).get_continuation( msg, prev_continue )
def list_messages(self, max_messages = None, mailbox = "INBOX", **options ):
if 'from_uid' in options: from_uid = options['from_uid']
else: from_uid = None
if 'since' in options: since = options['since']
else: since = None
if from_uid == 'None' or from_uid == '':
log( "Bad 'from_uid' entry in continuation!" )
from_uid = None
if since == 'None' or since == '':
log( "Bad 'since' entry in continuation!" )
since = None
if self.mailbox and self.mailbox != mailbox:
if not self.dry:
self.unwrap( self.connection.expunge( ) )
log( "CLOSING MAILBOX `%s` IN ORDER TO SELECT MAILBOX `%s`" % (self.mailbox, mailbox) )
self.unwrap( self.connection.close() )
self.mailbox = None
mailbox_info = self.unwrap( self.connection.select( mailbox ) )
self.mailbox = mailbox
if from_uid:
if since:
log( "IGNORING since-date, because from_uid is given" )
re = self.unwrap( self.connection.uid( "SEARCH", "(UID %s:*)" % from_uid ) )
elif since:
since = as_datetime( since )
t = as_imap_date( since )
trace("searching for messages since \"%s\"" % t)
#NOTE: IMAP disregards time and timezone when filtering by date! (yes, that's in the spec. wtf?)
re = self.unwrap( self.connection.uid( "SEARCH", "(SINCE \"%s\")" % t ) )
else:
re = self.unwrap( self.connection.uid( "SEARCH", "ALL" ) )
message_uids = re[0].split()
if max_messages and len(message_uids) > max_messages:
message_uids = message_uids[-max_messages:]
if len(message_uids) == 0:
return {}
log( "FETCHING UID RANGE %s:%s" % (message_uids[0], message_uids[-1]) )
#TODO: actually fetch range, not individual messages?
messages = {}
for uid in message_uids:
trace( "fetching message %s" % str(uid) )
msg = self.peek_headers(uid)
try:
#Skip deleted entries in IMAP inbox
if '\\Deleted' in msg.xx_flags:
continue
except:
pass
try:
#skip UIDs we have already processed
if from_uid and from_uid >= msg.xx_uid:
continue
except:
pass
messages[uid] = msg
return messages
def peek_headers(self, uid):
re = self.unwrap( self.connection.uid('FETCH', uid, "(BODY.PEEK[HEADER] FLAGS INTERNALDATE RFC822.SIZE UID)") )
msg = self.response_to_message( re )
return msg
def fetch_message(self, uid, peek = False):
if peek:
re = self.unwrap( self.connection.uid('FETCH', uid, "(BODY.PEEK[] FLAGS INTERNALDATE RFC822.SIZE UID)") )
else:
re = self.unwrap( self.connection.uid('FETCH', uid, "(BODY[] FLAGS INTERNALDATE RFC822.SIZE UID)") )
msg = self.response_to_message( re )
return msg
imap_size_pattern = re.compile(r"[(\s]RFC822.SIZE\s+(\d+)[)\s]")
imap_uid_pattern = re.compile(r"[(\s]UID\s+(\d+)[)\s]")
imap_date_pattern = re.compile(r"[(\s]INTERNALDATE\s+\"(.*?)\"[)\s]")
imap_flags_pattern = re.compile(r"[(\s]FLAGS\s+\((.*?)\)[)\s]")
def response_to_message( self, re ):
raw = re[0][1]
msg = rfc822parser.parsestr( raw, True )
#attach extra meta info provided by imap
meta = re[0][0] + re[1] #WTF python?!
#print "META: %s" % meta
m = Imap4Service.imap_size_pattern.search(meta);
if m:
msg.xx_size = int(m.group(1))
m = Imap4Service.imap_uid_pattern.search(meta);
if m:
msg.xx_uid = int(m.group(1))
m = Imap4Service.imap_date_pattern.search(meta);
if m:
msg.xx_date_received = as_datetime(m.group(1))
m = Imap4Service.imap_flags_pattern.search(meta);
if m:
msg.xx_flags = imaplib.ParseFlags(m.group(1))
return msg
def add_message(self, msg, folder, date = None, flags = ""):
#XXX: use msg.xx_date_received if present??
if not date:
date = datetime.datetime.now()
if isinstance(date, datetime.datetime):
trace( "converting datetime %s" % date )
date = as_imap_date_time( date )
if isinstance(date, str) and not quoted_string_pattern.match( date ):
date = '"%s"' % date
trace( "posting with date %s" % date )
self.unwrap( self.connection.append(folder, flags, date, msg.as_string()) )
def delete_message(self, uid):
self.update_flags( uid, '\Deleted' )
def move_message(self, uid, folder):
self.copy_message( uid, folder )
self.delete_message( uid )
def copy_message(self, uid, folder):
#FIXME: preserve keywords!
#print "copy %s, %s" % (uid, folder)
self.unwrap( self.connection.uid('COPY', uid, folder) )
def update_flags(self, uid, flags):
# hack: imaplib is too keen on quoting. according to spec, lags should never be quoted,
# bit imaplib forces quotes when seeing a backslapsh, as in \Deleted.
# We wrap the flags in parentacies to avoid this.
if not alphanumeric_pattern.match( flags ):
if not whitespace_pattern.search( flags ):
flags = "(%s)" % flags
self.unwrap( self.connection.uid('STORE', uid, '+FLAGS', flags) )
#TODO: implement MailTransportService based on sendmail CLI interface
class SmtpService ( MailTransportService ):
def __init__(self, **connection_spec):
MailService.__init__(self, **connection_spec)
def unwrap( self, response ):
if int(response[0]) > 400 :
raise Exception("SMTP error: %s" % response[1])
return response[1]