Search code examples
pythongmailimaplib

python3 - imaplib: randomly(?) can' fetch received email


def get_email_body(self, email):
    user = self.email_usr
    password = self.app_email_pwd
    connection = imaplib.IMAP4_SSL('imap.gmail.com')
    connection.login(user, password)
    connection.list()
    connection.select('"INBOX"')
    time.sleep(5)
    result_search, data_search = connection.search(None, 'TO', email, 'SUBJECT', '"some subject"')
    required_email = data_search[0]
    result_fetch, data_fetch = connection.fetch(required_email, '(RFC822)')
    email_body_string = data_fetch[0][1].decode('utf-8')
    confirmation_link = self.parse_confirmation_link(email_body_string)
    return confirmation_link

This function works like 2 times of 4 runs. Usually it fails with:

self = <imaplib.IMAP4_SSL object at 0x7fa853614b00>, name = 'FETCH'

tag = b'JAAL5'
def _command_complete(self, name, tag):
    # BYE is expected after LOGOUT
    if name != 'LOGOUT':
        self._check_bye()
    try:
        typ, data = self._get_tagged_response(tag)
    except self.abort as val:
        raise self.abort('command: %s => %s' % (name, val))
    except self.error as val:
        raise self.error('command: %s => %s' % (name, val))
    if name != 'LOGOUT':
        self._check_bye()
    if typ == 'BAD':
      raise self.error('%s command error: %s %s' % (name, typ, data))
E           imaplib.error: FETCH command error: BAD [b'Could not parse command']

/usr/lib/python3.4/imaplib.py:964: error

My suggestion was that sometimes email isn't delivered at the moment of .search that's why I added time.sleep (I'm searching for the email immediately after it was sent). Else I did try search while result_fetch is not 'OK' but is also didn't help. Any other suggestions?


Solution

  • oooops, my suggestion was correct, but time.sleep was in the incorrect place. Moved sleep before connection and all go smooth