def connect_imap():
m = imaplib.IMAP4_SSL("imap.gmail.com", 993)
print("{0} Connecting to mailbox via IMAP...".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
details = login_credentials()
m.login(details[0], details[1])
return m
m = connect_imap()
typ, data = m.search(None, 'ALL')
m.close()
m.logout()
上述代码的输出是:
2016-08-24 10:55:34 Connecting to mailbox via IMAP...
Traceback (most recent call last):
File "/home/zoikmail/Desktop/test.py", line 25, in <module>
typ, data = m.search(None, 'ALL')
File "/usr/lib/python2.7/imaplib.py", line 640, in search
typ, dat = self._simple_command(name, *criteria)
File "/usr/lib/python2.7/imaplib.py", line 1088, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/usr/lib/python2.7/imaplib.py", line 838, in _command
', '.join(Commands[name])))
imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED
[Finished in 1.2s with exit code 1]
[shell_cmd: python -u "/home/zoikmail/Desktop/test.py"]
[dir: /home/zoikmail/Desktop]
[path: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games]
上面的代码有什么问题?
成功连接到IMAP服务器后,您需要选择一个邮箱。 使用
m.select()
连接后、搜索前。
首先你需要使用该功能:
imap.select("INBOX")
之后您可以使用带有 imap.uid 的命令进行搜索。基本上,当您使用 imap.select 时,您会正确连接到邮件服务器。