gpt4 book ai didi

python - 如何在 python 2.7 中从邮件的有效负载中仅打印消息正文

转载 作者:行者123 更新时间:2023-12-01 08:32:03 24 4
gpt4 key购买 nike

我正在尝试打印消息,但收到不需要的文本。无法过滤。

#!/usr/bin/python
import imaplib
import email
import re
p = re.compile(r'Server Status')

mail = imaplib.IMAP4_SSL('stbeehive.yxz.com')
(retcode, capabilities) = mail.login('abc@yxz.com','passwd')
print retcode, capabilities
mail.list()
mail.select('Inbox')
n=0
(retcode, messages) = mail.search(None,'(UNSEEN)')
if retcode == 'OK':
for num in messages[0].split() :
print 'Processing '
n=n+1
typ, data = mail.fetch(num,'(RFC822)')
for response_part in data:
if isinstance(response_part, tuple):
original = email.message_from_string(response_part[1])
print original['From']
print original['Subject']
if original.is_multipart():
message = original.get_payload()[0]
print message
for line in message:
if p.findall(line):
print line
else:
print original.get_payload()

print n

当我尝试打印下面的消息时。我只想要其中的第三行。

Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
Server Status#XYZBSS##XYZ Running

我尝试在上面的代码中使用 re.compile 来过滤“服务器状态”,但出现以下错误。

  File "./mail.py", line 27, in <module>
for line in message:
File "/usr/lib64/python2.6/email/message.py", line 292, in __getitem__
return self.get(name)
File "/usr/lib64/python2.6/email/message.py", line 358, in get
name = name.lower()
AttributeError: 'int' object has no attribute 'lower'

最佳答案

如果没有看到该消息,这有点推测性,但看起来您正在提取带有标题和所有内容的正文部分。您想要找到正确的 body 部位,然后提取其有效负载。

如果没有实际的消息可供查看,则无法对此进行测试,但我猜测类似

             if original.is_multipart():
# Quick hack, should probably properly recurse
message = original.get_payload()[0].get_payload()
else:
message = original.get_payload()
#print message
for line in message.split('\n'):
if 'Server Status' in line: # look ma, no regex necessary
print line

关于python - 如何在 python 2.7 中从邮件的有效负载中仅打印消息正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53868240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com