-
Notifications
You must be signed in to change notification settings - Fork 1
/
getmail_fetch
executable file
·234 lines (207 loc) · 8.42 KB
/
getmail_fetch
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
#!/usr/bin/env python
import sys
if sys.hexversion < 0x2030300:
raise ImportError('getmail version 4 requires Python version 2.3.3 '
'or later')
import os
import socket
import poplib
from optparse import OptionParser
try:
from getmailcore import __version__, retrievers, destinations, message, \
logging
from getmailcore.exceptions import *
except ImportError, o:
sys.stderr.write('ImportError: %s\n' % o)
sys.exit(127)
log = logging.Logger()
log.addhandler(sys.stderr, logging.WARNING)
#######################################
class dummyInstance:
pass
#######################################
def blurb():
log.info('getmail_fetch version %s\n' % __version__)
log.info('Copyright (C) 1998-2012 Charles Cazabon. Licensed under the '
'GNU GPL version 2.\n')
#######################################
def error_exit(v, s):
sys.stderr.write(s + '\n')
sys.stderr.flush()
sys.exit(v)
#######################################
def go(retriever, destination, options, startmsg):
msgs_retrieved = 0
if options.verbose:
log.addhandler(sys.stdout, logging.INFO, maxlevel=logging.INFO)
blurb()
try:
if startmsg is not None:
destination.deliver_message(startmsg, False, False)
log.info('%s:\n' % retriever)
retriever.initialize(options)
destination.retriever_info(retriever)
nummsgs = len(retriever)
fmtlen = len(str(nummsgs))
for (msgnum, msgid) in enumerate(retriever):
msgnum += 1
size = retriever.getmsgsize(msgid)
log.info(' msg %*d/%*d (%d bytes) ...'
% (fmtlen, msgnum, fmtlen, nummsgs, size))
try:
msg = retriever.getmsg(msgid)
msgs_retrieved += 1
destination.deliver_message(msg, False, False)
log.info(' delivered')
retriever.delivered(msgid)
if options.delete:
retriever.delmsg(msgid)
log.info(', deleted')
log.info('\n')
except getmailDeliveryError, o:
error_exit(7, 'Delivery error: %s' % o)
try:
retriever.quit()
except getmailOperationError, o:
log.warning('Operation error during quit (%s)\n' % o)
except socket.timeout, o:
error_exit(8, 'Timeout error: %s' % o)
except socket.gaierror, o:
error_exit(9, 'gaierror: %s' % o)
except socket.error, o:
error_exit(10, 'Socket error: %s' % o)
except poplib.error_proto, o:
error_exit(11, 'Protocol error: %s' % o)
except getmailCredentialError, o:
error_exit(13, 'Credential error: %s' % o)
except getmailOperationError, o:
error_exit(12, 'Operational error: %s' % o)
log.info('%d messages retrieved\n' % msgs_retrieved)
#######################################
def main():
try:
parser = OptionParser(
version='%%prog %s' % __version__,
usage='%prog [options] server username password destination'
)
parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
help='output only on error')
parser.add_option('-v', '--verbose', action='store_true',
dest='verbose', default=True,
help='output informational messages '
'(default: verbose)')
parser.add_option('-m', '--message', action='store', dest='message',
help='deliver message from FILE first',
metavar='FILE')
parser.add_option('-p', '--port', action='store', type='int',
dest='port', metavar='PORT', default=None,
help='use server port PORT (default: POP: 110, '
'POP3-over-SSL: 995)')
parser.add_option('-d', '--delete', action='store_true',
dest='delete', default=False,
help='delete messages after retrieval (default: no)')
parser.add_option('-t', '--timeout', action='store', type='int',
dest='timeout', metavar='SECS', default=180,
help='use timeout SECS (default: 180)')
parser.add_option('-a', '--apop', action='store_true',
dest='apop', default=False,
help='use APOP authentication (default: no)')
parser.add_option('-s', '--ssl', action='store_true',
dest='ssl', default=False,
help='use POP3-over-SSL (default: no)')
(options, args) = parser.parse_args(sys.argv[1:])
if len(args) != 4:
raise getmailOperationError('incorrect arguments; try --help'
% args)
msg = None
if options.message is not None:
try:
f = open(options.message, 'rb')
msg = message.Message(fromfile=f)
except IOError, o:
error_exit(
1,
'Error reading message file "%s": %s' % (options.message, o)
)
instance = dummyInstance()
# Retriever
if options.ssl:
retriever_func = retrievers.BrokenUIDLPOP3SSLRetriever
port = options.port or 995
else:
retriever_func = retrievers.BrokenUIDLPOP3Retriever
port = options.port or 110
retriever_args = {
'getmaildir' : os.getcwd(),
'configparser' : instance,
'timeout' : options.timeout,
'server' : args[0],
'port' : port,
'username' : args[1],
'password' : args[2],
'use_apop' : options.apop
}
try:
retriever = retriever_func(**retriever_args)
retriever.checkconf()
except getmailOperationError, o:
error_exit(3, 'Error initializing retriever: %s' % o)
# Destination
destination = args[3].strip()
if destination.startswith('.') or destination.startswith('/'):
if destination.endswith('/'):
destination_func = destinations.Maildir
destination_args = {
'path' : destination,
'configparser' : instance,
}
else:
destination_func = destinations.Mboxrd
destination_args = {
'path' : destination,
'configparser' : instance,
}
elif destination.startswith('|'):
destination_func = destinations.MDA_external
parts = destination[1:].split()
cmd = parts[0]
arguments = str(tuple(parts[1:]))
destination_args = {
'path' : cmd,
'arguments' : arguments,
'allow_root_commands' : False,
'configparser' : instance,
}
else:
error_exit(4, 'Unknown destination type "%s"' % destination)
try:
destination = destination_func(**destination_args)
except getmailOperationError, o:
error_exit(
5, 'Error initializing destination "%s": %s' % (destination, o)
)
go(retriever, destination, options, msg)
except KeyboardInterrupt:
error_exit(6, 'Operation aborted by user (keyboard interrupt)')
except getmailOperationError, o:
error_exit(7, 'Operation error: %s' % o)
except getmailConfigurationError, o:
error_exit(8, 'Configuration error: %s' % o)
except StandardError, o:
log.critical('\nException: please read docs/BUGS and include the '
'following information in any bug report:\n\n')
log.critical(' getmail_fetch version %s\n' % __version__)
log.critical(' Python version %s\n\n' % sys.version)
log.critical('Unhandled exception follows:\n')
exc_type, value, tb = sys.exc_info()
import traceback
tblist = (traceback.format_tb(tb, None)
+ traceback.format_exception_only(exc_type, value))
if type(tblist) != list:
tblist = [tblist]
for line in tblist:
log.critical(' %s\n' % line.rstrip())
sys.exit(9)
#######################################
if __name__ == '__main__':
main()