0

我可以打印每封电子邮件。我想要做的是在每封电子邮件中搜索一个字符串,如果它有字符串,则返回 true 或 false。我怎样msg才能做到这一点?

conn.select(readonly=1) # Select inbox or default namespace
(retcode, messages) = conn.search(None, '(UNSEEN)')
if retcode == 'OK':
    for num in messages[0].split(' '):
        print 'Processing :', messages
        typ, data = conn.fetch(num,'(RFC822)')
        msg = email.message_from_string(data[0][1])
        typ, data = conn.store(num,'-FLAGS','\\Seen')
        if retcode == 'OK':
            print data,'\n',30*'-'
            for line in msg:
                if "Subject: Thanks for your Walmart.com Order" in line:
                    print line

conn.close()
4

1 回答 1

1

当你有一个 email 对象msg时,你可以这样做:

message_lines = msg.get_payload().splitlines()

然后循环遍历每一行:

for line in message_lines:
    if 'Walmart' in line:
        pass # do whatever

但同样,请注意有效载荷是什么......

另一种选择是让 IMAP 服务器完成工作:

(retcode, messages) = conn.search(None, '(UNSEEN) (TEXT walmart)')

这将对需要获取的消息数量进行子集化,然后您可以根据需要应用更复杂的匹配...

也可以按主题搜索(如果这最终是您想要做的):

(retcode, messages) = conn.search(None, '(UNSEEN) (SUBJECT Thanks for your Walmart.com Order)')
于 2012-11-03T20:10:23.990 回答