-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimap-util
executable file
·144 lines (136 loc) · 4.67 KB
/
imap-util
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
#!/usr/bin/env python
#=======================================================================
# Various actions on IMAP folders
#=======================================================================
from __future__ import print_function
import sys
import ptimap
import argparse
try:
import configparser
except ImportError: # PY2
import ConfigParser as configgparser
import os
import os.path
import time
import logging
_log = logging.getLogger('imap-util')
def die(msg,code=1):
print(msg, file=sys.stderr)
sys.exit(code)
ap = argparse.ArgumentParser()
ap.add_argument('-v','--verbose', action='store_true',
help='Show progress')
ap.add_argument('-d','--debug', action='store_true',
help='Low-level tracing')
ap.add_argument('account',
help='Account name in ~/.imap')
sub = ap.add_subparsers(dest='action', metavar='action',
help='Action to perform')
login = sub.add_parser('login')
capabilities = sub.add_parser('capabilities')
folders = sub.add_parser('folders')
folders.add_argument('pattern', nargs='?')
select = sub.add_parser('select')
select.add_argument('folder')
older = sub.add_parser('older')
older.add_argument('folder')
older.add_argument('days', type=int)
delete_older = sub.add_parser('delete-older')
delete_older.add_argument('folder')
delete_older.add_argument('days', type=int)
list_ = sub.add_parser('list')
backup = sub.add_parser('backup')
backup.add_argument('-c','--cachedir', default='.cache')
backup.add_argument('folder')
backup.add_argument('destdir')
args = ap.parse_args()
if args.debug:
logging.basicConfig(level=logging.DEBUG)
elif args.verbose:
logging.basicConfig(level=logging.INFO)
rc = '~/.imap'
acct, action = args.account, args.action
try:
account = ptimap.Account.from_file(rc, acct)
except configparser.NoSectionError:
die("%s: No such account '%s' in %s" % (ap.prog, acct, rc))
account.login()
if action=='login':
pass
elif action=='capabilities':
print(account._imap.capabilities)
elif action=='namespace':
ns = account.namespace()
print(ns)
elif action=='folders':
if args.pattern:
lst = account.folders(args.pattern)
else:
lst = account.folders()
for f in lst:
print(f.path)
elif action=='list':
for folder in account.folders():
print(folder.path)
for email in folder.iteremails():
print(' %s' % email.subject)
elif action=='select':
folder = args.folder
nmsgs = account.select(folder)
print("%d message(s) in %s" % (nmsgs, folder))
elif action in ('older','delete-older'):
folder, days = args.folder, args.days
account.select(folder)
date = time.localtime(time.time() - int(days) * 86400)
# sdate = imaplib.Time2Internaldate(date)
# print('sdate:',sdate)
# lst = account.search('SEEN','UNDELETED',
# 'BEFORE',sdate)
sdate = time.strftime('%e-%b-%Y', date)
lst = account.search('SEEN','UNDELETED',
'(BEFORE %s)' % sdate)
if action=='older':
print(lst)
elif action=='delete-older':
if len(lst):
todel = lst
#todel = lst[:100]
#account.copy(todel,cp.get(acct,'trash'))
account.copy(todel, 'Trash')
account.store(todel,('\\Deleted',))
print("Deleted %s message%s from %s" % (
len(lst), len(lst)==1 and '' or 's', folder))
elif action=='backup':
from ptimap.linkcache import LinkCache
lc = LinkCache(args.cachedir, 2)
match = [f for f in account.folders() if f.path == args.folder]
if not match:
raise ValueError('Folder %s not found' % args.folder)
folder = match[0]
destdir = args.destdir
if not os.path.exists(destdir):
os.makedirs(destdir)
for em in folder.iteremails():
msgid = em.message_id
if msgid is None:
_log.info('No message-id for email with subject %r' % em.subject)
# Synthesize a message-id equivalent
date = em.date or ''
addr = em.from_[0]
key = ('%s~%s' % (date, addr)).replace(' ','_')
else:
key = msgid.lstrip('<').rstrip('>')
key = key.replace('%','%25').replace('/','%2F')
_log.info('key=%s size=%d', key, em.size)
if lc.has_cached(key):
_log.info('cache hit for %s', key)
lc.use_cached(key, os.path.join(destdir, key))
else:
destpath = os.path.join(destdir, key)
_log.info('Writing to %s', destpath)
with open(destpath, 'w') as f:
em.write_to(f)
lc.add_to_cache(key, destpath)
else:
die("Unknown action '%s'" % action)