import os, imaplib, re, hashlib, shutil, getopt
class IMAPServer: def __init__(self, server, port, ssl, usr, psd): if ssl: self.__server=imaplib.IMAP4_SSL(server, port) else: self.__server=imaplib.IMAP4(server, port) self.__server.debug=4 self.__server.login(usr, psd) print usr , " loged in"
def __parse_paren_list(self, row): """Parses the nested list of attributes at the start of a LIST response""" assert(row[0] == '(' ) row = row[1:]
result = []
name_attrib_re = re.compile("^s*(\\[a-zA-Z0-9_]+)s*")
while row[0] != ')': if row[0] == '(': paren_list, row = parse_paren_list(row) result.append(paren_list) else: match = name_attrib_re.search(row) assert(match != None) name_attrib = row[match.start():match.end()] row = row[match.end():] name_attrib = name_attrib.strip() result.append(name_attrib)
assert(')' == row[0]) row = row[1:]
return result, row
def __parse_string_list(self, row): """Parses the quoted and unquoted strings at the end of a LIST response""" slist = re.compile('s*(?:"([^"]+)")s*|s*(S+)s*').split(row) return [s for s in slist if s]
def __parse_list(self, row): """Prases response of LIST command into a list""" row = row.strip() paren_list, row = self.__parse_paren_list(row) string_list = self.__parse_string_list(row) assert(len(string_list) == 2) return [paren_list] + string_list
def __get_hierarchy_delimiter(self): """Queries the imapd for the hierarchy delimiter, eg. '.' in INBOX.Sent""" typ, data = self.__server.list('', '') assert(typ == 'OK') assert(len(data) == 1) lst = self.__parse_list(data[0]) hierarchy_delim = lst[1] if 'NIL' == hierarchy_delim: hierarchy_delim = '.'
return hierarchy_delim
def __convert_utf7(self, str): p=str.split("&") rst=p[0]+("+"+p[1]).decode("utf-7") return rst
def get_mailbox_names(self): delim = self.__get_hierarchy_delimiter()
typ, data = self.__server.list() assert(typ == 'OK')
names=[] for row in data: lst = self.__parse_list(row) foldername = lst[2]
unicodename=foldername if foldername.find('&')>=0: unicodename=self.__convert_utf7(foldername)
names.append((foldername,unicodename)) return names
def get_mail(self, mailbox, dir, fromid=1): type, num= self.__server.select(mailbox)
for mail_id in range(fromid,int(num[0])+1): type=None try: type, msg_data=self.__server.fetch(mail_id, "(RFC822 BODY[TEXT])") except: print "Get ", mail_id, " failed"
if type!="OK": continue
content=msg_data[0][1] bodyMD5=msg_data[1][1].strip()
print "Saving ",mail_id, " total ", num[0]
filename=hashlib.md5(bodyMD5).hexdigest() file=open(os.path.join(dir,filename), "wb") file.write(content) file.flush() file.close()
def upload_mail(self, mailbox, content): print self.__server.append(mailbox,0,0,content)
|