-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgmail.py
More file actions
196 lines (161 loc) · 5.7 KB
/
gmail.py
File metadata and controls
196 lines (161 loc) · 5.7 KB
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
#!/usr/bin/env python
"""Upload email messages from a list of Maildir to Google Mail."""
# Forked from:
# Scott Yang's maildir2gmail script
# permission granted over email on Dec 3, 2010 EST
#
# By:
# Raja Kapur <raja.kapur@gmail.com>
#
# https://github.com/aonic/owa2gmail
# maildir2gmail: http://scott.yang.id.au/2009/01/migrate-emails-maildir-gmail/
# Based on maildir2gmail.py by Scott Yang
# http://scott.yang.id.au/2009/01/migrate-emails-maildir-gmail/
#
# Copyright (C) 2010 Raja Kapur <raja.kapur@gmail.com>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
__version__ = '0.1'
import email
import email.Header
import email.Utils
import os
import sys
import time
import socket
socket.timeout(300)
class Gmail(object):
def __init__(self, options):
self.username = options.username
self.password = options.password
self.folder = options.folder
if self.folder == 'inbox':
self.folder = 'INBOX'
else:
self.folder = '[Gmail]/%s' % self.folder
self.__database = None
self.__imap = None
def __del__(self):
if self.__database is not None:
try:
self.__database.close()
except:
pass
self.__database = None
if self.__imap is not None:
try:
self.__imap.logout()
self.__imap.close()
except:
pass
self.__imap = None
def append(self, content):
#if self.check_appended(filename):
# return
#content = open(filename, 'rb').read()
if content.endswith('\x00\x00\x00'):
log('Skipping "%s" - corrupted' % os.path.basename(filename))
return
message = email.message_from_string(content)
timestamp = parsedate(message['date'])
if not timestamp:
log('Skipping "%s" - no date' % os.path.basename(filename))
return
subject = decode_header(message['subject'])
log('Sending "%s" (%d bytes)' % (subject, len(content)))
del message
self.imap.append(self.folder, '(\\Seen)', timestamp, content)
#self.mark_appended(filename)
def check_appended(self, filename):
return os.path.basename(filename) in self.database
def mark_appended(self, filename):
self.database[os.path.basename(filename)] = '1'
@property
def database(self):
import dbhash
if self.__database is None:
dbname = os.path.abspath(os.path.splitext(sys.argv[0])[0] + '.db')
self.__database = dbhash.open(dbname, 'w')
return self.__database
@property
def imap(self):
from imaplib import IMAP4_SSL
if self.__imap is None:
if not self.username or not self.password:
raise Exception('Username/password not supplied')
self.__imap = IMAP4_SSL('imap.gmail.com')
self.__imap.login(self.username, self.password)
log('Connected to Gmail IMAP')
return self.__imap
def decode_header(value):
result = []
for v, c in email.Header.decode_header(value):
try:
if c is None:
v = v.decode()
else:
v = v.decode(c)
except (UnicodeError, LookupError):
v = v.decode('iso-8859-1')
result.append(v)
return u' '.join(result)
def encode_unicode(value):
if isinstance(value, unicode):
for codec in ['iso-8859-1', 'utf8']:
try:
value = value.encode(codec)
break
except UnicodeError:
pass
return value
def log(message):
print '[%s]: %s' % (time.strftime('%H:%M:%S'), encode_unicode(message))
def main():
from optparse import OptionParser
parser = OptionParser(
description=__doc__,
usage='%prog [options]',
version=__version__
)
parser.add_option('-f', '--folder', dest='folder', default='All Mail',
help='Folder to store the emails. [default: %default]')
parser.add_option('-p', '--password', dest='password',
help='Password to log into Gmail')
parser.add_option('-u', '--username', dest='username',
help='Username to log into Gmail')
options, args = parser.parse_args()
gmail = Gmail(options)
for dirname in args:
for filename in os.listdir(dirname):
filename = os.path.join(dirname, filename)
if os.path.isfile(filename):
try:
gmail.append(filename)
except:
log('Unable to send %s' % filename)
raise
def parsedate(value):
if value:
value = decode_header(value)
value = email.Utils.parsedate_tz(value)
if isinstance(value, tuple):
timestamp = time.mktime(tuple(value[:9]))
if value[9]:
timestamp -= time.timezone + value[9]
if time.daylight:
timestamp += 3600
return time.localtime(timestamp)
if __name__ == '__main__':
main()