我正在尝试打印消息,但收到不需要的文本。无法过滤。
#!/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'
答案 0 :(得分: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