Last active
September 29, 2016 20:42
-
-
Save olegbuevich/e7bbb382ec6a4b7d3a504fdd1d963f27 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# based on: http://www.php2python.com/wiki/function.imap-utf7-encode/ | |
def modified_base64(s): | |
s_utf7 = s.encode('utf-7') # | |
aaa = s_utf7[1:-1].decode().replace('/', ',') # rfc2060 | |
return aaa | |
def modified_unbase64(s): | |
s_utf7 = '+' + s.replace(',', '/') + '-' | |
return s_utf7.encode().decode('utf-7') | |
def encode_imap4_utf7(s, errors=None): | |
r = list() | |
_in = list() | |
for c in s: | |
if ord(c) in range(0x20, 0x25) or ord(c) in range(0x27, 0x7e): | |
if _in: | |
r.extend(['&', modified_base64(''.join(_in)), '-']) | |
del _in[:] | |
r.append(str(c)) | |
elif ord(c) == 0x26: # символ & | |
if _in: | |
r.extend(['&', modified_base64(''.join(_in)), '-']) | |
del _in[:] | |
r.append('&-') | |
else: | |
_in.append(c) | |
if _in: | |
r.extend(['&', modified_base64(''.join(_in)), '-']) | |
return ''.join(r), len(s) | |
def decode_imap4_utf7(s): | |
r = list() | |
if s.find('&-') != -1: | |
s = s.split('&-') | |
i = len(s) | |
for subs in s: | |
i -= 1 | |
r.append(decode_imap4_utf7(subs)) | |
if i != 0: | |
r.append('&') | |
else: | |
# шаблон для строки символов, экранированных & - (т.е. то, что надо декодировать) | |
regex = re.compile(r'[&]\S+?[-]') | |
sym = re.split(regex, s) | |
# если подстрок много | |
if len(regex.findall(s)) > 1: | |
i = 0 | |
r.append(sym[i]) | |
for subs in regex.findall(s): | |
r.append(decode_imap4_utf7(subs)) | |
i += 1 | |
r.append(sym[i]) | |
# только 1 подстрока | |
elif len(regex.findall(s)) == 1: | |
r.append(sym[0]) | |
r.append(modified_unbase64(regex.findall(s)[0][1:-1])) | |
r.append(sym[1]) | |
# ничего декодировать не надо | |
else: | |
r.append(s) | |
return ''.join(r) | |
status, folders = mailbox.list() | |
for item in folders: | |
print(decode_imap4_utf7(item.decode())) | |
print(mailbox.select(encode_imap4_utf7('"[Gmail]/Вся почта"')[0])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment