Search code examples
pythonimapimaplib

Converting string from email


I am trying to write a program that will scan my email inbox and take further action if the first word in the email is "Password". However, my specific condition if message_str[:9].lower() == 'password': always defaults to false, even though the string being compared is clearly 'password' as I have tested by making print statements. Why is this so?

code:

import imapclient, pyzmail, time, sys

while True:
    imapObj = imapclient.IMAPClient('imap.gmail.com', ssl=True)
    imapObj.login('xxxxxxxx@gmail.com', sys.argv[1])
    imapObj.select_folder('INBOX', readonly=False)
    UIDs = imapObj.search(['SINCE', '01-Mar-2021', 'FROM', 'xxxxxxxx@gmail.com'])
    rawMessages = imapObj.fetch(UIDs, ['BODY[]'])

    for i in UIDs:
        message = pyzmail.PyzMessage.factory(rawMessages[i][b'BODY[]'])
        if message.text_part:
            message_str = message.text_part.get_payload().decode(message.text_part.charset)
            a = (repr(message_str))
            if message_str[:9].lower() == 'password':
                continue

Solution

  • 'password' has 8 not 9 letters, so you need to use message_str[:8].lower()