python - 使用 Python 解析包含子部分的多部分电子邮件

标签 python

我正在使用此函数来解析电子邮件。我能够解析“简单”的多部分电子邮件,但当电子邮件定义多个边界(子部分)时,它会产生错误(UnboundLocalError:分配前引用的局部变量“html”)。我希望脚本将文本和 html 部分分开并仅返回 html 部分(除非没有 html 部分,否则返回文本)。

def get_text(msg):
text = ""
if msg.is_multipart():
    for part in msg.get_payload():
        if part.get_content_charset() is None:
            charset = chardet.detect(str(part))['encoding']
        else:
            charset = part.get_content_charset()
        if part.get_content_type() == 'text/plain':
            text = unicode(part.get_payload(decode=True),str(charset),"ignore").encode('utf8','replace')
        if part.get_content_type() == 'text/html':
            html = unicode(part.get_payload(decode=True),str(charset),"ignore").encode('utf8','replace')
    if html is None:
        return text.strip()
    else:
        return html.strip()
else:
    text = unicode(msg.get_payload(decode=True),msg.get_content_charset(),'ignore').encode('utf8','replace')
    return text.strip()

最佳答案

就像评论说的那样,您总是检查 html 但仅在其中一种特定情况下声明它。这就是错误告诉你的,你在分配它之前引用了 html。在 python 中,如果某物尚未分配给任何东西,则检查它是否为 None 是无效的。例如打开python交互提示符:

>>> if y is None:
...   print 'none'
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined

如您所见,您不能仅仅通过检查 none 来查看变量是否存在。回到您的具体案例。

您需要先将 html 设置为 None,然后稍后您将检查它是否仍然是 None。即像这样编辑您的代码:

def get_text(msg):
text = ""
if msg.is_multipart():
    html = None
    for part in msg.get_payload():
        if part.get_content_charset() is None:
            charset = chardet.detect(str(part))['encoding']
        else:
            charset = part.get_content_charset()
        if part.get_content_type() == 'text/plain':
            text = unicode(part.get_payload(decode=True),str(charset),"ignore").encode('utf8','replace')
        if part.get_content_type() == 'text/html':
            html = unicode(part.get_payload(decode=True),str(charset),"ignore").encode('utf8','replace')
    if html is None:
        return text.strip()
    else:
        return html.strip()
else:
    text = unicode(msg.get_payload(decode=True),msg.get_content_charset(),'ignore').encode('utf8','replace')
    return text.strip()

这解释了更多: http://code.activestate.com/recipes/59892-testing-if-a-variable-is-defined/

关于python - 使用 Python 解析包含子部分的多部分电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4824376/

相关文章:

python - 临时文件目录最终是否被系统清除

python - TensorFlow安装问题Mac

python - 如何为与 setuptools、distribute 等一起使用的 twistd/twisted 插件编写 setup.py?

python - 删除 Pandas Dataframe 列范围内每列总和小于 10 的列

python - Spark : IllegalArgumentException: 'Unsupported class file major version 55'

python - itertools.ifilter 与 IPython 并行

python - 为什么此 python 代码中的内存使用量增加?

python - 如何在 numpy ndarray 中将具有相同行和列的值设置为零?

python - 使用正则表达式 python 捕获字符串中的整数列表

python - 配置 usjon 以将日期时间返回为日期时间对象而不是 int utc 时间戳