获取/读取邮件消息并输出纯文本



Windows OS上使用Python 2.7Gmail-试图获取和阅读电子邮件正文

# Parse the email message
msg = email.message_from_string(msg_data[0][1].decode('UTF-8'))
# Extract the "FROM" field
from_field = msg['FROM']
# Extract the received timestamp
received_timestamp = msg['Date']
msg_body = None
# Extract the body of the email
if msg.is_multipart():
for part in msg.walk():
# if part.get_content_type() == 'text/html':
if part.get_content_type() == 'text/plain':
msg_body = part.get_payload(decode=True).decode()
break
else:
msg_body = msg.get_payload(decode=True).decode()

# Print the results
print('FROM: {}'.format(from_field))
print('Received: {}'.format(received_timestamp))
print('Body:n{}'.format(msg_body))

我能够打印"from_field""received_timestamp"变量-所以我知道它击中正确的电子邮件/消息id。

我尝试了"text/html"-这给了我很好的HTML格式的电子邮件(但我想要纯文本),我尝试了"text/plain"这给了我"None"

我想我不必使用"beautifulsoup""re"来获取纯文本。

我搜索了这个论坛,并试图理解现有的帖子,但无法弄清楚我的代码中缺少什么。

任何提示或指针将是有帮助的-提前感谢!

尝试使用msg.get_payload()代替msg.get_payload(decode=True).decode()get_payload()方法应该返回纯文本内容,而不需要额外的解码。

如果这不起作用,但text/html给了你html,那么也许你可以使用python的内置html库来提取它。就像

html_body = part.get_payload(decode=True).decode()
msg_body = html.unescape(html_body).replace('r', '').replace('n', ' ')

最新更新