-
Notifications
You must be signed in to change notification settings - Fork 0
/
imap-mailfilter.py
executable file
·2760 lines (2257 loc) · 85.5 KB
/
imap-mailfilter.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
#!/usr/bin/env python3
#
# filter emails in IMAP accounts
#
# written by: Andreas Scherbaum <[email protected]>
#
import re
import os
import stat
import sys
if sys.version_info[0] < 3:
reload(sys)
sys.setdefaultencoding('utf8')
import logging
import tempfile
import argparse
import yaml
import string
import sqlite3
import datetime
import atexit
import shlex
import imaplib
imaplib._MAXLINE = 10000000
import email
import email.header
from email.parser import HeaderParser
from email.parser import Parser
import email
import random
import gzip
import zlib
from subprocess import Popen
try:
from urlparse import urljoin # Python2
except ImportError:
from urllib.parse import urljoin # Python3
import smtplib
from email.mime.text import MIMEText
from html.parser import HTMLParser
import requests
from socket import error as SocketError
import errno
sys.path.insert(0, os.path.abspath('./python-twitter'));
# the module name "twitter" will clash with something preinstalled
# we load the module in the "python-twitter" directory, with a different alias name
# https://github.com/bear/python-twitter
import twitter as TW
# start with 'info', can be overriden by '-q' later on
logging.basicConfig(level = logging.INFO,
format = '%(levelname)s: %(message)s')
#######################################################################
# Message Parser class
class MyMessageParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
def get_list():
return self._links
def parse_message(self, message):
self._links = []
self.reset()
parser = Parser()
parsed = parser.parsestr(str(message), headersonly=False)
if (parsed.is_multipart() is True):
for part in parsed.walk():
if (part.get_content_type() == "multipart" or part.get_content_type() == "multipart/alternative"):
continue
if (part.get_content_type() == "text/plain"):
self.find_urls(str(part.get_payload(decode = True)))
if (part.get_content_type() == "text/html"):
self.feed(str(part.get_payload(decode = True)))
else:
if (parsed.get_content_type() == "text/plain"):
self.find_urls(str(parsed.get_payload(decode = True)))
if (parsed.get_content_type() == "text/html"):
self.feed(str(parsed.get_payload(decode = True)))
self._links = list(dict.fromkeys(self._links))
return self._links
def handle_starttag(self, tag, attrs):
#print("Encountered a start tag:", tag)
if (tag == "a"):
#print("Encountered a start tag:", tag)
for name, value in attrs:
if (name == "href"):
#print(name, value)
#print(name, "=", value)
# the values are not exactly clean all the time
if (value.startswith('=')):
value = value[len('='):]
if (value.startswith('3D')):
value = value[len('3D'):]
if (value.startswith('"')):
value = value[len('"'):]
self._links.append(str(value))
#def handle_endtag(self, tag):
# print("Encountered an end tag:", tag)
#def handle_data(self, data):
# print("Encountered some data:", data)
def find_urls(self, message):
urls = re.findall('https?://[^\r\n\t\s\\\\]+', message)
for u in urls:
self._links.append(str(u))
# end HTMLParser class
#######################################################################
#######################################################################
# Config class
class Config:
def __init__(self):
self.__cmdline_read = 0
self.__configfile_read = 0
self.arguments = False
self.argument_parser = False
self.configfile = False
self.config = False
self.output_help = True
self.retweets = {}
if (os.environ.get('HOME') is None):
logging.error("$HOME is not set!")
sys.exit(1)
if (os.path.isdir(os.environ.get('HOME')) is False):
logging.error("$HOME does not point to a directory!")
sys.exit(1)
# config_help()
#
# flag if help shall be printed
#
# parameter:
# - self
# - True/False
# return:
# none
def config_help(self, config):
if (config is False or config is True):
self.output_help = config
else:
print("")
print("invalid setting for config_help()")
sys.exit(1)
# print_help()
#
# print the help
#
# parameter:
# - self
# return:
# none
def print_help(self):
if (self.output_help is True):
self.argument_parser.print_help()
# add_retweet()
#
# add to the retweet counter
#
# parameter:
# - self
# - name of Twitter account
# return:
# none
def add_retweet(self, name):
if (name in self.retweets.keys()):
self.retweets[name] += 1
else:
self.retweets[name] = 1
# get_retweets()
#
# get number of current retweets for a Twitter account
#
# parameter:
# - self
# - name of Twitter account
# return:
# - number of retweets in current run
def get_retweets(self, name):
if (name not in self.retweets.keys()):
return 0
return self.retweets[name]
# set_retweets()
#
# set the number of current retweets for a Twitter account
#
# parameter:
# - self
# - name of Twitter account
# - new value
# return:
# none
def set_retweets(self, name, value):
try:
value = int(value)
if (value < 0):
raise ValueError
except ValueError:
logging.error("Value '%s' is not an integer" % (str(value)))
sys.exit(1)
self.retweets[name] = int(value)
# parse_parameters()
#
# parse commandline parameters, fill in array with arguments
#
# parameter:
# - self
# return:
# none
def parse_parameters(self):
parser = argparse.ArgumentParser(description = 'filter emails in IMAP accounts',
add_help = False)
self.argument_parser = parser
parser.add_argument('--help', default = False, dest = 'help', action = 'store_true', help = 'show this help')
parser.add_argument('-c', '--config', default = '', dest = 'config', help = 'configuration file')
# store_true: store "True" if specified, otherwise store "False"
# store_false: store "False" if specified, otherwise store "True"
parser.add_argument('-v', '--verbose', default = False, dest = 'verbose', action = 'store_true', help = 'be more verbose')
parser.add_argument('-q', '--quiet', default = False, dest = 'quiet', action = 'store_true', help = 'run quietly')
# parse parameters
args = parser.parse_args()
if (args.help is True):
self.print_help()
sys.exit(0)
if (args.verbose is True and args.quiet is True):
self.print_help()
print("")
print("Error: --verbose and --quiet can't be set at the same time")
sys.exit(1)
if not (args.config):
self.print_help()
print("")
print("Error: configfile is required")
sys.exit(1)
if (args.verbose is True):
logging.getLogger().setLevel(logging.DEBUG)
if (args.quiet is True):
logging.getLogger().setLevel(logging.ERROR)
self.__cmdline_read = 1
self.arguments = args
return
# load_config()
#
# load configuration file (YAML)
#
# parameter:
# - self
# return:
# none
def load_config(self):
if not (self.arguments.config):
return
logging.debug("config file: " + self.arguments.config)
if (self.arguments.config and os.path.isfile(self.arguments.config) is False):
self.print_help()
print("")
print("Error: --config is not a file")
sys.exit(1)
# the config file holds sensitive information, make sure it's not group/world readable
st = os.stat(self.arguments.config)
if (st.st_mode & stat.S_IRGRP or st.st_mode & stat.S_IROTH):
self.print_help()
print("")
print("Error: --config must not be group or world readable")
sys.exit(1)
try:
with open(self.arguments.config, 'r') as ymlcfg:
config_file = yaml.safe_load(ymlcfg)
except:
print("")
print("Error loading config file")
sys.exit(1)
# verify all account entries
errors_in_config = False
try:
t = config_file['accounts']
except KeyError:
print("")
print("Error: missing 'accounts' entry in config file")
errors_in_config = True
if (errors_in_config is True):
sys.exit(1)
self.configfile = config_file
self.__configfile_read = 1
return
# end Config class
#######################################################################
#######################################################################
# Database class
class Database:
def __init__(self, config):
self.config = config
# database defaults to a hardcoded file
self.connection = sqlite3.connect(os.path.join(os.environ.get('HOME'), '.imap-mailfilter', 'imap-mailfilter.sqlite'))
self.connection.row_factory = sqlite3.Row
# debugging
#self.drop_tables()
self.init_tables()
#sys.exit(0);
atexit.register(self.exit_handler)
def exit_handler(self):
self.connection.close()
# init_tables()
#
# initialize all missing tables
#
# parameter:
# - self
# return:
# none
def init_tables(self):
if (self.table_exist('seen_emails') is False):
logging.debug("need to create table seen_emails")
self.table_seen_emails()
# drop_tables()
#
# drop all existing tables
#
# parameter:
# - self
# return:
# none
def drop_tables(self):
if (self.table_exist('seen_emails') is True):
logging.debug("drop table seen_emails")
self.drop_table('seen_emails')
# table_exist()
#
# verify if a table exists in the database
#
# parameter:
# - self
# - table name
# return:
# - True/False
def table_exist(self, table):
query = "SELECT name FROM sqlite_master WHERE type='table' AND name=?"
result = self.execute_one(query, [table])
if (result is None):
return False
else:
return True
# drop_table()
#
# drop a specific table
#
# parameter:
# - self
# - table name
# return:
# none
def drop_table(self, table):
# there is no sane way to quote identifiers in Python for SQLite
# assume that the table name is safe, and that the author of this module
# never uses funny table names
query = 'DROP TABLE "%s"' % table
self.execute_one(query, [])
# run_query()
#
# execute a database query without parameters
#
# parameter:
# - self
# - query
# return:
# none
def run_query(self, query):
cur = self.connection.cursor()
cur.execute(query)
self.connection.commit()
# execute_one()
#
# execute a database query with parameters, return single result
#
# parameter:
# - self
# - query
# - list with parameters
# return:
# - result
def execute_one(self, query, param):
cur = self.connection.cursor()
cur.execute(query, param)
result = cur.fetchone()
self.connection.commit()
return result
# execute_query()
#
# execute a database query with parameters, return result set
#
# parameter:
# - self
# - query
# - list with parameters
# return:
# - result set
def execute_query(self, query, param):
cur = self.connection.cursor()
cur.execute(query, param)
result = cur.fetchall()
self.connection.commit()
return result
# table_seen_emails()
#
# create the 'seen_emails' table
#
# parameter:
# - self
# return:
# none
def table_seen_emails(self):
query = """CREATE TABLE seen_emails (
id INTEGER PRIMARY KEY NOT NULL,
added_ts DATETIME DEFAULT CURRENT_TIMESTAMP,
msgid TEXT NOT NULL,
account TEXT NOT NULL,
rule TEXT NOT NULL
)"""
self.run_query(query)
# remember_msg_id()
#
# store Msg-ID
#
# parameter:
# - self
# - Msg-ID
# - Account
# - Rule name
# return:
# none
def remember_msg_id(self, msg_id, account, rule):
if (self.msgid_seen_before(msg_id, account, rule) is True):
return
query = """INSERT INTO seen_emails
(msgid, account, rule)
VALUES (?, ?, ?)"""
self.execute_one(query, [msg_id, account, rule])
# msgid_seen_before()
#
# verify if a Msg-ID was seen before
#
# parameter:
# - self
# - Msg-ID
# - Account
# - Rule name
# return:
# - True/False
def msgid_seen_before(self, msg_id, account, rule):
query = """SELECT *
FROM seen_emails
WHERE msgid = ?
AND account = ?
AND rule = ?"""
res = self.execute_one(query, [msg_id, account, rule])
if (res is None):
# not in database
return False
else:
return True
# end Database class
#######################################################################
#######################################################################
# IMAP class
class ImapConnection:
def __init__(self, config, account_name, server, username, password, ssl = True):
self.config = config
self.account_name = account_name
self.server = server
self.username = username
self.password = password
self.ssl = ssl
self.current_folder = ''
if (self.server == 'imap.gmail.com'):
# required for flag operations like "delete" (move to trash instead)
self.gmail = True
else:
self.gmail = False
# open TCP connection
error = False
try:
if (ssl is True):
self.connection = imaplib.IMAP4_SSL(self.server)
else:
self.connection = imaplib.IMAP4(self.server)
except TimeoutError:
error = True
logging.error("Connection '%s' timed out" % self.account_name)
if (self.ssl is False):
logging.info("Try using SSL mode instead")
if (error is True):
# outside of except block, else this would re-raise the exception
raise imaplib.IMAP4.error("Connection '%s' timed out" % self.account_name)
# login into IMAP server
error = False
try:
resp, data = self.connection.login(self.username, self.password)
except imaplib.IMAP4.error:
logging.error("Invalid username/password combination for '%s'" % self.account_name)
try:
error = True
self.connection.shutdown()
except:
pass
if (error is True):
raise imaplib.IMAP4.error("Invalid username/password combination for '%s'" % self.account_name)
# should see an 'OK' response here
if (resp != 'OK'):
logging.error("Invalid response from IMAP server for '%s'" % self.account_name)
try:
self.connection.logout()
except:
pass
raise imaplib.IMAP4.error("Invalid response from IMAP server for '%s'" % self.account_name)
logging.debug("Connection for '%s' established" % self.account_name)
# print the list of folders
# print(self.connection.list())
atexit.register(self.exit_handler)
return
# exit_handler()
#
# shutdown connection
#
# parameter:
# - self
# return:
# none
def exit_handler(self):
try:
self.connection.expunge()
self.connection.shutdown()
self.connection.logout()
except:
pass
# select_imap_folder()
#
# select a specific IMAP folder
#
# parameters:
# - self
# - folder name
# return:
# - True/False
def select_imap_folder(self, folder):
# first check if the folder exists
logging.debug("select IMAP folder: %s" % folder)
folder_tmp = '"' + folder + '"'
try:
e = self.connection.status(folder_tmp, '(MESSAGES)')
except imaplib.IMAP4.error:
logging.error("Failed to fetch folder status")
return False
except SocketError:
logging.error("Failed to fetch folder status")
return False
if (e[0] != 'OK'):
logging.error("Selected folder (%s) does not exist" % folder)
return False
try:
e = self.connection.select(folder_tmp)
except imaplib.IMAP4.error:
logging.error("Failed to select folder: %s" % folder_tmp)
return False
if (e[0] != 'OK'):
logging.error("Can't select folder (%s)" % folder)
return False
self.current_folder = folder
return True
# selected_folder()
#
# return the currently selected folder
#
# parameters:
# - self
# return:
# - folder name
def selected_folder(self):
return self.current_folder
# search()
#
# search in current IMAP folder
#
# parameters:
# - self
# - search option
# - search criteria
# - additional UIDs to limit the search
# return:
# - list with uids, or empty list
def search(self, what, criteria, orig_uids = []):
# make sure the criteria is plain ascii, as IMAP does not support searching for UTF-8
try:
criteria.encode('ascii')
except UnicodeEncodeError:
logging.error("Can't support UTF-8 in search criterta: %s", criteria)
return []
logging.debug("search (before lexer): %s / %s" % (what, criteria))
# split and parse all strings
criteria = shlex.split(criteria)
logging.debug("search (after lexer): %s / %s" % (what, criteria))
# check that only the same search criteria is used
# mixing different criteria doesn't really work without
# an elaborate parser
last_op = ''
for search in criteria:
if (last_op == '' and (search == 'AND' or search == 'OR')):
last_op = search
continue
if (search == 'AND' or search == 'OR'):
if (search != last_op):
logging.error("Can't mix different search criteria (%s / %s)!" % (last_op, search))
return []
# loop over the criteria and decide if each entry is a search criteria or a keyword
final_uids = False
last_op = ''
for search in criteria:
logging.debug("criteria: %s" % (search))
if (search == 'AND' or search == 'OR'):
last_op = search
continue
if (search == 'NOT'):
logging.error("search for 'NOT' is currently not supported!")
return []
# this will search for messages in the currently selected folder
# if a list with UIDs is specified, the search will be limited to this UIDs - hence further redefining the search
search = what + ' "%s"' % search
if (len(orig_uids) > 0):
search += ' UID %s' % ",".join(orig_uids)
logging.debug("partial search: " + str(search))
try:
result, messages = self.connection.uid('search', None, search)
except KeyError:
logging.error("Test")
sys.exit(1)
except imaplib.IMAP4.error:
logging.error("Search failed!")
sys.exit(1)
result_uids = messages[0].split()
result_uids = [x.decode() for x in result_uids]
logging.debug("partial UIDs: " + str(result_uids))
# handle results based on last found operation
if (last_op == 'AND'):
# $final_uids must already be set, the first keyword can't be 'AND'
if (final_uids is False):
logging.error("First keyword can't be 'AND'!")
return []
# this will only select the uids which are in both result sets
new_uids = []
for t in final_uids:
if (t in result_uids):
new_uids.append(t)
final_uids = new_uids
elif (last_op == 'OR'):
# $final_uids must already be set, the first keyword can't be 'OR'
if (final_uids is False):
logging.error("First keyword can't be 'OR'!")
return []
# this will select the uids which are in either of the result sets
for t in result_uids:
if (t not in final_uids):
final_uids.append(t)
else:
# regular result (can only be set once)
if (final_uids is False):
final_uids = result_uids
else:
logging.error("Missing keyword between searches!")
return []
if (final_uids is False):
logging.error("No search happened!")
return []
logging.debug("final UIDs: " + str(final_uids))
return final_uids
# fetch()
#
# fetch a specific message
#
# parameters:
# - self
# - uid (which is unique)
# return:
# - headers, as dictionary - False if message does not exist
# - body
# - complete email message
def fetch(self, uid):
logging.debug("Fetching message %s" % str(uid))
try:
res, msg = self.connection.uid('fetch', uid, '(RFC822)')
except imaplib.IMAP4.error as msg:
logging.error(str(msg))
sys.exit(1)
if (res != 'OK'):
logging.error("Something went wrong fetching email uid '%s'" % str(uid))
return False, False, False
if (msg[0] is None):
# message is (probably) deleted
return False, False, False
try:
raw_msg = msg[0][1].decode('utf-8')
except UnicodeDecodeError:
raw_msg = str(msg[0][1])
except TypeError:
logging.error("No message to decode: '%s'" % str(uid))
logging.error("%s" % str(msg))
logging.error("%s" % str(res))
return False, False, False
email_msg = email.message_from_string(raw_msg)
body = ''
if (email_msg.is_multipart()):
# message is multipart, extract all parts except images
for mp in email_msg.walk():
mp_type = mp.get_content_type()
mp_cd = str(mp.get('Content-Disposition'))
# skip plain attachments
if (mp_type == 'text/plain' and 'attachment' not in mp_cd):
try:
body += mp.get_payload(decode = True).decode()
except UnicodeDecodeError:
body += str(mp.get_payload(decode = True))
else:
# message is not multipart, just extract it
try:
body = email_msg.get_payload(decode=True).decode()
except UnicodeDecodeError:
body = str(email_msg.get_payload(decode=True))
header_parser = HeaderParser()
headers = header_parser.parsestr(raw_msg)
#print(headers.keys())
return headers, body, email_msg
# labels()
#
# fetch labels for a specific message
#
# parameters:
# - self
# - uid (which is unique)
# return:
# - headers, as dictionary - False if message does not exist
# - body
# - complete email message
def labels(self, uid):
if (self.gmail is False):
logging.error("Only possible for Gmail accounts!")
return
logging.debug("Fetching message %s" % str(uid))
try:
res, msg = self.connection.uid('fetch', uid, '(X-GM-LABELS)')
except imaplib.IMAP4.error as msg:
logging.error(str(msg))
sys.exit(1)
if (res != 'OK'):
logging.error("Something went wrong fetching labels for email uid '%s'" % str(uid))
return False, False, False
labels_tmp = re.search(r'X-GM-LABELS \(([^\)]+)\)', str(msg))
if (labels_tmp):
labels = shlex.split(str(labels_tmp.group(1)))
else:
labels = list()
# chicken-egg problem:
# GMail does not return the currently selected IMAP folder
# in the list of labels, but the message can be in that
# folder as well - no one knows for sure
# since most searches start in a specific folder,
# add the currently selected folder to this list
labels.append(self.selected_folder())
return labels
# add_label()
#
# Add label to a GMail message
#
# parameters:
# - self
# - uid (which is unique)
# - label
# return:
# none
def add_label(self, uid, label):
if (self.gmail is False):
logging.error("Only possible for Gmail accounts!")
return
logging.debug("Add label '%s' to message %s" % (label, str(uid)))
try:
if (label == "Inbox"):
res, msg = self.connection.uid('MOVE', uid, '"INBOX"')
elif (label == self.selected_folder()):
res, msg = self.connection.uid('MOVE', uid, '"' + label + '"')
else:
res, msg = self.connection.uid('STORE', uid, '+X-GM-LABELS', '"' + label + '"')
except imaplib.IMAP4.error as msg:
logging.error(str(msg))
sys.exit(1)
if (res != 'OK'):
logging.error("Something went wrong adding label '%s' to message '%s'" % (label, str(uid)))
return
return
# remove_label()
#
# Remove label from a GMail message