【问题标题】:how can I determine whether an email header is base64 encoded如何确定电子邮件标头是否为 base64 编码
【发布时间】:2015-03-20 16:56:49
【问题描述】:

使用 email.header 包,我可以做到

the_text,the_charset = decode_header(inputText)

获取电子邮件标题的字符集,其中 inputText 是通过类似的命令检索的

inputText = msg.get('From')

以 From: 标头为例。

为了提取该标头的标头编码,我必须做这样的事情吗?:

the_header_encoding = email.charset.Charset(the_charset).header_encoding

也就是说,我是否必须根据字符集的名称创建 Charset 类的实例(这甚至可以工作吗?),或者有没有办法更直接地从标头本身提取标头编码?

【问题讨论】:

  • decode_header 根据需要从 base64 或引用的可打印编码解码标头; the_charset 组件是标头中声明的 codec
  • @MartijnPieters 这就是我对 decode_header 的理解,但由于其他原因,我仍然需要知道标头是否经过 base64 编码。我可以通过我建议的方法获取该信息吗?还是有更简单的方法?
  • 我不确定我是否理解您在寻找什么。你想知道header是否使用Encoded-Word syntax,如果是,是否使用了base64或quoted-printable?
  • 请注意,标头可以包含多个编码字部分,并且每个部分都可能使用不同编码!在那种情况下你想要整个列表吗?

标签: python-2.7 email


【解决方案1】:

Encoded-Message 标头可以包含 1 行或多行,并且每行可以使用不同的编码,或者根本不使用编码。

您必须自己解析编码类型,每行一个。使用正则表达式:

import re

quopri_entry = re.compile(r'=\?[\w-]+\?(?P<encoding>[QB])\?[^?]+?\?=', flags=re.I)
encodings = {'Q': 'quoted-printable', 'B': 'base64'}

def encoded_message_codecs(header):
    used = []
    for line in header.splitlines():
        entry = quopri_entry.search(line)
        if not entry:
            used.append(None)
            continue
        used.append(encodings.get(entry.group('encoding').upper(), 'unknown'))
    return used

这将返回从quoted-printablebase64unknownNone 中提取的字符串列表,如果该行没有使用 Encoded-Message。

【讨论】:

    猜你喜欢
    • 2010-09-24
    • 2014-08-23
    • 2012-02-24
    • 2011-12-30
    • 2012-04-24
    • 2015-02-06
    • 2011-12-09
    • 2010-09-12
    • 2011-11-21
    相关资源
    最近更新 更多