python3 - imaplib:随机(?)无法获取收到的电子邮件

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

这个函数的工作原理相当于 4 次运行的 2 次。通常它会失败:

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

我的建议是,有时电子邮件在 .search 时未送达,这就是我添加 time.sleep 的原因(我在电子邮件发送后立即搜索)。 否则我确实尝试搜索 result_fetch 不是 'OK' 但也没有帮助。 还有其他建议吗?

糟糕,我的建议是正确的,但是 time.sleep 放错了地方。在连接之前移动睡眠,一切顺利