Python的IMAP文件夹路径编码(IMAP UTF7)

2024-05-28 07:02:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道Python中是否存在用于IMAP4 UTF-7文件夹路径编码的“正式”函数/库。

imapInstance.list()中,我得到以下路径IMAP UTF-7编码:

'(\\HasNoChildren) "." "[Mails].Test&AOk-"',

如果我执行以下编码:

(u"[Mails].Testé").encode('utf-7')

我得到:

'[Mails].Test+AOk-'

它是UTF-7,但不是IMAP UTF-7编码的。Test+AOk-而不是Test&AOk- 我需要一个官方函数或库来获取IMAP UTF-7编码版本。


Tags: 函数test路径文件夹编码listutfencode
3条回答

我编写了一个非常简单的IMAP UTF7 python 3实现,它遵循了规范,而且似乎可以工作。(“foo\rbar\n\n\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    

考虑到这段代码的简单性,我将其设置在公共域中,因此可以随意使用它。

IMAPClient包具有使用IMAP修改过的UTF-7进行编码和解码的功能。查看IMAPClient.imap_utf7模块。这个模块可以单独使用,也可以只使用IMAPClient,它可以透明地处理文件夹名称的编码和解码。

项目的主页是:http://imapclient.freshfoo.com/

示例代码:

from imapclient import imap_utf7
decoded = imap_utf7.decode('&BdAF6QXkBdQ-')

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

相关问题 更多 >