我想知道Python中是否存在用于IMAP4 UTF-7文件夹路径编码的“官方”函数/库。
在imapInstance.list()中,我得到以下路径IMAP 7编码:
'(\\HasNoChildren) "." "[Mails].Test&AOk-"',如果我执行以下编码:
(u"[Mails].Testé").encode('utf-7')我得到了:
'[Mails].Test+AOk-'它是UTF-7但不是IMAP UTF-7编码。Test+AOk-而不是Test&AOk-,我需要一个官方函数或库来获得IMAP 7编码版本。
发布于 2012-10-10 00:01:27
IMAPClient包具有使用修改后的UTF-7进行编码和解码的功能。请看一下IMAPClient.imap_utf7模块。这个模块可以独立使用,也可以只使用IMAPClient,它透明地处理文件夹名的编码和解码。
该项目的主页是:http://imapclient.freshfoo.com/
示例代码:
from imapclient import imap_utf7
decoded = imap_utf7.decode('&BdAF6QXkBdQ-')发布于 2017-08-21 06:00:22
我写了一个非常简单的IMAP UTF7 python3实现,它遵循这个规范,而且看起来还不错。(“foo\rbar\n\r\r”和许多其他往返,'&BdAF6QXkBdQ-','Test&Co',"Mails.Test&AOk-“和'~peter/mail/&ZeVnLIqe-/&U,BTFw-‘行为如预期)。
#works with python 3
import base64
def b64padanddecode(b):
"""Decode unpadded base64 data"""
b+=(-len(b)%4)*'=' #base64 padding (if adds '===', no valid padding anyway)
return base64.b64decode(b,altchars='+,',validate=True).decode('utf-16-be')
def imaputf7decode(s):
"""Decode a string encoded according to RFC2060 aka IMAP UTF7.
Minimal validation of input, only works with trusted data"""
lst=s.split('&')
out=lst[0]
for e in lst[1:]:
u,a=e.split('-',1) #u: utf16 between & and 1st -, a: ASCII chars folowing it
if u=='' : out+='&'
else: out+=b64padanddecode(u)
out+=a
return out
def imaputf7encode(s):
""""Encode a string into RFC2060 aka IMAP UTF7"""
s=s.replace('&','&-')
iters=iter(s)
unipart=out=''
for c in s:
if 0x20<=ord(c)<=0x7f :
if unipart!='' :
out+='&'+base64.b64encode(unipart.encode('utf-16-be')).decode('ascii').rstrip('=')+'-'
unipart=''
out+=c
else : unipart+=c
if unipart!='' :
out+='&'+base64.b64encode(unipart.encode('utf-16-be')).decode('ascii').rstrip('=')+'-'
return out 考虑到这段代码的简单性,我将其设置为公共领域,因此可以随意使用它。
发布于 2015-08-17 22:37:33
不过,imapclient的实现有点问题:
x = "foo\rbar\n\n\n\r\r"
imap_utf7.decode(imap_utf7.encode(x))结果:
>> 'foo&bar\n\n\r-'编辑:
经过一些研究后,我发现了一个在MailPile中的实现,它在这个测试中不会在往返编码中失败。如果您感兴趣,我还将它移植到了Python3:https://github.com/MarechJ/py3_imap_utf7
https://stackoverflow.com/questions/12776679
复制相似问题