-
Notifications
You must be signed in to change notification settings - Fork 0
/
gmb.py
127 lines (108 loc) · 3.34 KB
/
gmb.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
#!/usr/bin/python
import imaplib
import string, random
import StringIO, rfc822
import os
from datetime import *
import time
# config
BACKUP_DIR = ""
BACKUP_IMAP_FOLDER = "[Gmail]/Todos"
SERVER = "imap.gmail.com"
USER = ""
PASSWORD = ""
# constants
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"]
STAT_OK = "OK"
DATETIME_FORMAT = "%Y-%m-%d"
class GMBackup:
def __init__(self, server, user, password, dst_dir):
self.server = server
self.user = user
self.password = password
self.dst_dir = dst_dir
self.conn = None
def connect(self):
# connect to server
self.conn = imaplib.IMAP4_SSL(self.server)
self.conn.login(self.user, self.password)
def backup(self, from_date = None, to_date = None):
status, num = self.conn.select(BACKUP_IMAP_FOLDER, True)
total_cnt = int(num[0])
if status != STAT_OK:
return False
day_cntr = 1
last_day = None
cfgf = os.path.join(self.dst_dir, "gb.conf")
try:
f = open(cfgf, "r")
last_d = f.read().strip()
last_d = datetime.strptime(last_d, DATETIME_FORMAT)
f.close()
except:
last_d = None
if last_d is not None:
search_d = "%.2d-%s-%.4d" % (last_d.day, MONTHS[last_d.month-1],
last_d.year) #d.strftime("%d-%b-%Y")
else:
search_d = None
# list items on server
if search_d is None:
search_str = "ALL"
else:
search_str = "(SINCE %s)" % search_d
resp, items = self.conn.search(None, search_str)
items = string.split(items[0])
cntr = 0
# fetch items
for i in items:
cntr += 1
# get full message
resp, data = self.conn.fetch(i, "(RFC822)")
text = data[0][1]
file = StringIO.StringIO(text)
message = rfc822.Message(file)
print '* [%d%%] %d/%d fetching' % (int(100 * cntr / len(items)), cntr, len(items),),
try:
print message['date']
except:
pass
try:
t = time.mktime(rfc822.parsedate(message['date']))
d = date.fromtimestamp(t)
except:
d = date(1980,1,1)
if last_day == d:
day_cntr += 1
else:
last_day = d
day_cntr = 1
# save it
pth = self.getpath(d)
if not os.path.exists(pth):
os.makedirs(pth)
fpth = os.path.join(pth, str(day_cntr) + ".eml")
f = open(fpth, "w")
f.write(text)
f.close()
# save last processed message timestamp
f = open(cfgf, "w")
f.write(d.strftime(DATETIME_FORMAT))
f.close()
def getpath(self, d):
return reduce(os.path.join, [self.dst_dir, str(d.year), str(d.month),
str(d.day)])
def disconnect(self):
self.conn.logout()
if __name__ == "__main__":
gmb = GMBackup(SERVER, USER, PASSWORD, dst_dir = BACKUP_DIR)
gmb.connect()
done = False
while not done:
try:
gmb.backup()
except Exception, e:
print e
done = True
gmb.disconnect()