python3 - imaplib:random(?)can'获取收到的电子邮件

时间:2016-04-26 08:22:45

标签: python gmail imaplib

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不是&#39; OK&#39;但也没有帮助。 还有其他建议吗?

1 个答案:

答案 0 :(得分:0)

oooops,我的建议是正确的,但是time.sleep是在错误的地方。在连接之前移动睡眠并且一切顺利