首页 > 解决方案 > 从电子邮件中解析出正文和表格

问题描述

我目前正在使用以下方法在 Python 中获取电子邮件的正文/内容:

import email
message = email.message_from_file(open(file))
messages = [part.get_payload() for part in message.walk() if part.get_content_type() == 'text/plain']

在大多数情况下,这似乎工作得很好,但我注意到有时有些 html 表没有被拾取。它开始于

<html>
<style type='text/css">

是否只是添加或part.get_content_tye() == 'text/css'

标签: pythonhtmlemailparsing

解决方案


如果我不得不猜测,我猜你需要添加'text/html'。

但是,您应该能够通过检查该变量的内容来确定电子邮件中的内容类型。

import email
message = email.message_from_file(open(file))


# Remove the content-type filter completely
messages = [(part.get_payload(), part.get_content_type()) for part in message.walk()]


# print the whole thing out so that you can see what content-types are in there.
print(message)

这将帮助您查看其中的内容类型,然后您可以过滤您需要的内容类型。


推荐阅读