【发布时间】: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 将在今年早些时候终止。