【问题标题】:How to print just message body from payload of a mail in python 2.7如何在 python 2.7 中仅从邮件的有效负载中打印消息正文
【发布时间】:2019-05-20 22:47:12
【问题描述】:

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

#!/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'

【问题讨论】:

  • 您是否有理由为此需要使用 Python 2.7?新开发绝对应该针对推荐和支持的语言版本,即 Python 3。
  • @tripleee 不幸的是,python3 尚未在我的组织中获得批准。所以,我不得不忍受python2.7一段时间。
  • 您的组织正在挑战极限。按照最初的时间表,Python 2 将在今年早些时候终止。

标签: python email imaplib


【解决方案1】:

在没有看到消息的情况下,这是一种轻微的推测,但看起来您正在提取带有标题和所有内容的正文部分。您想找到正确的身体部位,然后提取其有效负载。

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

             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

【讨论】:

  • 谢谢它的工作。只有一个问题来了。该行包含 80 多个单词。在一行中,它给出了多达 77 个单词。其余的单词将进入下一行。知道为什么会这样吗?
  • 它可能是用 Quoted Printable 编码的;它用“=”符号打破长行。你在你的消息中看到了流浪 = 吗?
  • Python 应该在您请求有效负载时清除所有 QP,但是一个 reguar 文本/纯文本消息的行数通常不应超过 80 个字符。同样,没有看到消息,我们只能推测。如果消息是format=flowed,即使消息源物理拆分为多行,它也会呈现为一行;但 Python 只会看到物理线。
猜你喜欢
  • 2014-03-04
  • 1970-01-01
  • 2011-04-18
  • 2015-01-16
  • 2017-03-22
  • 2013-10-23
  • 2017-02-08
  • 1970-01-01
  • 2012-05-05
相关资源
最近更新 更多