문제

I can print each email. What I want to do though is search each email for a string and return true of false if it has the string. How can I parase msg to do this?

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()
도움이 되었습니까?

해결책

As you've got an email object msg, then you can do:

message_lines = msg.get_payload().splitlines()

Then loop over each line:

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

But again, be careful of what the payload is...

The other option, is to have the IMAP server do the work:

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

This will subset the number of messages that need to be fetched and then you can apply more complex matching if required...

What's also possible is to search by subject (if that's ultimately what you want to do):

(retcode, messages) = conn.search(None, '(UNSEEN) (SUBJECT Thanks for your Walmart.com Order)')
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top